package com.corpgovernment.organization.controller;

import static com.corpgovernment.api.organization.model.org.front.ListOrgTreeRequest.QuerySceneTypeEnum.BOOKING_RELATION_ADD_USER;
import static com.corpgovernment.permission.config.PermissionFilter.DATA_PERMISSION_ORG_ID_LIST;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.Collator;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import com.alibaba.fastjson.JSON;
import com.corpgovernment.common.enums.ExceptionCodeEnum;
import com.corpgovernment.api.applytrip.enums.ApplyTripEmployeeEnum;
import com.corpgovernment.api.organization.model.employee.ListEmployeeByConditionRequest;
import com.corpgovernment.api.organization.model.employee.ListEmployeeByConditionResponse;
import com.corpgovernment.api.organization.model.settlement.QueryEmployeeInfoWithPermissionRequest;
import com.corpgovernment.api.organization.model.settlement.QueryEmployeeInfoWithPermissionResponse;
import com.corpgovernment.common.utils.ObjectStringTrimUtils;
import com.ctrip.corp.obt.generic.security.context.SecurityContext;
import com.corpgovernment.organization.vo.ListEmployeeInOrgVO;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.http.util.TextUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.corpgovernment.api.applytrip.enums.ApplyTripEmployeeEnum;
import com.corpgovernment.api.basic.dto.OrgDTO;
import com.corpgovernment.api.basic.request.UserLoginRequest;
import com.corpgovernment.api.costcenter.model.CostCenter;
import com.corpgovernment.api.costcenter.service.ICostCenterService;
import com.corpgovernment.api.messageadvice.enums.MsgBizType;
import com.corpgovernment.api.messageadvice.vo.MessageVo;
import com.corpgovernment.api.operatelog.chooseconstant.ChooseBusinesstype;
import com.corpgovernment.api.organization.bo.FindManageFuzzyRequestBO;
import com.corpgovernment.api.organization.bo.SearchEmployeeInfoRequestBO;
import com.corpgovernment.api.organization.bo.UpdateEmployeeRequestBO;
import com.corpgovernment.api.organization.bo.UpdateEmployeeResponseBO;
import com.corpgovernment.api.organization.dto.EmployeeInfoVo;
import com.corpgovernment.api.organization.dto.request.EmployeeByUidRequestVo;
import com.corpgovernment.api.organization.enums.CardTypeEnum;
import com.corpgovernment.api.organization.enums.UserOrgRelationStatusEnum;
import com.corpgovernment.api.organization.model.bookingrelation.MbBookingRelationVo;
import com.corpgovernment.api.organization.model.bookingrelation.UidOrgIdEntry;
import com.corpgovernment.api.organization.model.employee.EmployeeInfoBo;
import com.corpgovernment.api.organization.model.enums.WholeGroupQueryEnum;
import com.corpgovernment.api.organization.model.ffpinfo.UserFfpFrontVo.UserFfpFrontVo;
import com.corpgovernment.api.organization.model.idcard.front.CardType;
import com.corpgovernment.api.organization.model.idcard.front.UserIdCardFrontVo;
import com.corpgovernment.api.organization.model.org.GetOrgTreeResponse;
import com.corpgovernment.api.organization.model.org.OrgInfoVo;
import com.corpgovernment.api.organization.model.org.front.ListOrgTreeRequest.SortTypeEnum;
import com.corpgovernment.api.organization.model.org.queryEmployee.QueryEmployeeRequest;
import com.corpgovernment.api.organization.model.org.queryEmployee.QueryEmployeeResponse;
import com.corpgovernment.api.organization.model.orguserrelation.MbUserOrgRelationVo;
import com.corpgovernment.api.organization.model.orguserrelation.request.AddUserInfoRequest;
import com.corpgovernment.api.organization.model.orguserrelation.request.ListUserOrgRelationForLoginRequest;
import com.corpgovernment.api.organization.model.orguserrelation.response.ListUserOrgRelationForLoginResponse;
import com.corpgovernment.api.organization.model.post.front.PositionEmployeeListVo;
import com.corpgovernment.api.organization.model.settlement.QueryEmployeeInfoWithPermissionRequest;
import com.corpgovernment.api.organization.model.settlement.QueryEmployeeInfoWithPermissionResponse;
import com.corpgovernment.api.organization.model.user.NameInfoBo;
import com.corpgovernment.api.organization.model.user.employee.EmployeeInfoRequestBo;
import com.corpgovernment.api.organization.model.user.employee.EmployeeInfoResponseBo;
import com.corpgovernment.api.organization.model.user.employee.EmployeeOrgVo;
import com.corpgovernment.api.organization.model.user.employee.OrgEmployeeVo;
import com.corpgovernment.api.organization.model.user.employee.OrgPostLogVo;
import com.corpgovernment.api.organization.model.user.employee.UserDignityVo;
import com.corpgovernment.api.organization.model.user.employee.UserOrgRelation;
import com.corpgovernment.api.organization.model.user.employee.front.DepartmentEmployeeVo;
import com.corpgovernment.api.organization.model.user.employee.front.EmployeePageVo;
import com.corpgovernment.api.organization.model.user.employee.front.EmployeeSubscriptionRequest;
import com.corpgovernment.api.organization.model.user.employee.front.EmployeeSubscriptionResponse;
import com.corpgovernment.api.organization.model.user.employee.front.GetEmpInPositionRequest;
import com.corpgovernment.api.organization.model.user.employee.front.GetEmpInPositionResponse;
import com.corpgovernment.api.organization.model.user.employee.front.GetEmployeeDetailRequest;
import com.corpgovernment.api.organization.model.user.employee.front.GetLeaderRequest;
import com.corpgovernment.api.organization.model.user.employee.front.GetLeaderResponse;
import com.corpgovernment.api.organization.model.user.employee.front.GetPositionInfoRequest;
import com.corpgovernment.api.organization.model.user.employee.front.GetUnAuditEmployeeListRequest;
import com.corpgovernment.api.organization.model.user.employee.front.ListEmployeeRequest;
import com.corpgovernment.api.organization.model.user.employee.front.OperateEmployeeRequest;
import com.corpgovernment.api.organization.model.user.employee.front.SearchAllEmpListRequest;
import com.corpgovernment.api.organization.model.user.employee.front.SearchAllEmpListResponse;
import com.corpgovernment.api.organization.model.user.employee.front.SubmitSelectEmpRequest;
import com.corpgovernment.api.organization.model.user.employee.front.SubmitSelectEmpVo;
import com.corpgovernment.api.organization.model.user.employee.request.AddUserInfoFrontInitRequest;
import com.corpgovernment.api.organization.model.user.employee.request.AddUserInfoFrontRequest;
import com.corpgovernment.api.organization.model.user.employee.request.ChangeUserIdentityRequest;
import com.corpgovernment.api.organization.model.user.employee.request.DeleteUserOrgRelationByOrgIdRequest;
import com.corpgovernment.api.organization.model.user.employee.request.DeleteUserOrgRelationRequest;
import com.corpgovernment.api.organization.model.user.employee.request.FindUserOrgRelationStatusRequest;
import com.corpgovernment.api.organization.model.user.employee.request.GetUserInfoRequest;
import com.corpgovernment.api.organization.model.user.employee.request.ListEmployeeInAdminRequest;
import com.corpgovernment.api.organization.model.user.employee.request.ListEmployeeInOrgRequest;
import com.corpgovernment.api.organization.model.user.employee.request.ListUserRequest;
import com.corpgovernment.api.organization.model.user.employee.request.OperatorUserDignityRequest;
import com.corpgovernment.api.organization.model.user.employee.request.SetUpLeaderRequest;
import com.corpgovernment.api.organization.model.user.employee.request.UpdateEmployeeRequest;
import com.corpgovernment.api.organization.model.user.employee.request.UpdateUserOrgRelationRequest;
import com.corpgovernment.api.organization.model.user.employee.response.AddUserInfoFrontInitResponse;
import com.corpgovernment.api.organization.model.user.employee.response.DeleteUserOrgRelationByOrgIdResponse;
import com.corpgovernment.api.organization.model.user.employee.response.DeleteUserOrgRelationByOrgIdResponse.DeleteUserOrgRelationByOrgIdResultInfo;
import com.corpgovernment.api.organization.model.user.employee.response.GetUserInfoResponse;
import com.corpgovernment.api.organization.model.user.employee.response.ListEmployeeInAdminResponse;
import com.corpgovernment.api.organization.model.user.employee.response.ListEmployeeInOrgResponse;
import com.corpgovernment.api.organization.model.user.employee.response.ListUserResponse;
import com.corpgovernment.api.organization.model.user.employee.response.SaveEmpBaseInfoResponse;
import com.corpgovernment.api.organization.model.user.login.MbUserLoginVo;
import com.corpgovernment.api.permission.vo.BatchUpdateRole4UserReq;
import com.corpgovernment.api.permission.vo.GetUserRoleDetailRequest;
import com.corpgovernment.api.permission.vo.GetUserRoleListInfo;
import com.corpgovernment.api.permission.vo.GetUserRoleListResponse;
import com.corpgovernment.common.apollo.OrganizationApollo;
import com.corpgovernment.common.base.BaseUserInfo;
import com.corpgovernment.common.base.JSONResult;
import com.corpgovernment.common.base.Page;
import com.corpgovernment.common.common.CorpBusinessException;
import com.corpgovernment.common.enums.CardEnum;
import com.corpgovernment.common.handler.ICacheHandler;
import com.corpgovernment.common.operatelog.OperateLog;
import com.corpgovernment.job.dao.entity.db.EmployeeJobRelationDo;
import com.corpgovernment.job.dao.entity.db.JobDo;
import com.corpgovernment.job.dao.mapper.EmployeeJobRelationMapper;
import com.corpgovernment.job.dao.mapper.JobMapper;
import com.corpgovernment.organization.constant.CommonConst;
import com.corpgovernment.organization.constant.OrgEmployeeConst;
import com.corpgovernment.organization.constant.OrganizationConst;
import com.corpgovernment.organization.constant.OrganizationResponseCodeEnum;
import com.corpgovernment.organization.dataloader.ApprovalClientLoader;
import com.corpgovernment.organization.dataloader.db.MbOrgEmployeeLoader;
import com.corpgovernment.organization.dto.ListEmployeeQuery;
import com.corpgovernment.organization.dto.MbOrgEmployeeInfoDto;
import com.corpgovernment.organization.dto.OrgUserInfoPk;
import com.corpgovernment.organization.entity.db.MbFreshPassenger;
import com.corpgovernment.organization.entity.db.MbFreshPassengerRelation;
import com.corpgovernment.organization.entity.db.MbOrgEmployeeInfo;
import com.corpgovernment.organization.entity.db.MbOrgInfo;
import com.corpgovernment.organization.entity.db.MbOrgUserFfpinfo;
import com.corpgovernment.organization.entity.db.MbOrgUserIdcard;
import com.corpgovernment.organization.entity.db.MbPostInfo;
import com.corpgovernment.organization.entity.db.MbUserLogin;
import com.corpgovernment.organization.entity.db.MbUserOrgRelation;
import com.corpgovernment.organization.enumm.ExcelPostEnum;
import com.corpgovernment.organization.enumm.OrgTypeEnum;
import com.corpgovernment.organization.event.EmployeeActionEvent;
import com.corpgovernment.organization.mapper.MbUserOrgRelationMapper;
import com.corpgovernment.organization.producer.MultiTenantSendMessageProducer;
import com.corpgovernment.organization.service.BookingRelationService;
import com.corpgovernment.organization.service.IFreshPassengerService;
import com.corpgovernment.organization.service.IOrgUserIdCardService;
import com.corpgovernment.organization.service.IOrganizationEmployeeService;
import com.corpgovernment.organization.service.IOrganizationInfoService;
import com.corpgovernment.organization.service.IOrganizationNonEmployeeService;
import com.corpgovernment.organization.service.IOrganizationUserFfpService;
import com.corpgovernment.organization.service.IPostService;
import com.corpgovernment.organization.service.IUserLoginService;
import com.corpgovernment.organization.service.IUserOrgRelationService;
import com.corpgovernment.organization.service.RedemptionCodeService;
import com.corpgovernment.organization.service.impl.FreshPassengerRelationServiceImpl;
import com.corpgovernment.organization.util.AsyncTaskUtil;
import com.corpgovernment.organization.util.ExcelUtils;
import com.corpgovernment.organization.util.OrganizationUtil;
import com.corpgovernment.organization.util.OrganizationUtils;
import com.corpgovernment.organization.util.StrUtils;
import com.corpgovernment.organization.util.TokenValidUtil;
import com.corpgovernment.organization.vo.AgentPersonResponse;
import com.corpgovernment.organization.vo.EmployeeInfoListExcelVO;
import com.corpgovernment.organization.vo.ExcelCreateVO;
import com.corpgovernment.organization.vo.SearchCorpEmpRequest;
import com.corpgovernment.organization.vo.SearchCorpEmpResponse;
import com.corpgovernment.permission.entity.db.MbRole;
import com.corpgovernment.permission.entity.db.MbUserRole;
import com.corpgovernment.permission.service.RoleService;
import com.corpgovernment.permission.service.UserRoleService;
import com.corpgovernment.permission.service.UserService;
import com.corpgovernment.permission.vo.UserRole;
import com.corpgovernment.redis.cache.RoleResourceManager;
import com.corpgovernment.redis.cache.UserCacheManager;
import com.ctrip.corp.obt.generic.core.context.RequestContext;
import com.ctrip.corp.obt.generic.event.core.EventCenter;
import com.ctrip.corp.obt.generic.utils.CollectionUtils;
import com.ctrip.corp.obt.generic.utils.JsonUtils;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import com.ctrip.corp.obt.shard.sql.mybatis.interceptor.pagination.IPage;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * @author wangyujue
 */
@RestController
@RequestMapping("/employee")
@Slf4j
public class OrganizationEmployeeController {

    @Autowired
    private IOrganizationInfoService organizationInfoService;
    @Autowired
    private IPostService postService;
    @Autowired
    private IOrgUserIdCardService organizationUserIdCardService;
    @Autowired
    private IOrganizationUserFfpService organizationUserFfpService;
    @Autowired
    private IUserLoginService userLoginService;
    @Autowired
    private IFreshPassengerService freshPassengerService;
    @Autowired
    private IUserOrgRelationService userOrgRelationService;
    @Autowired
    private UserService userService;
    @Autowired
    private BookingRelationService bookingRelationService;
    @Autowired
    private IOrganizationNonEmployeeService organizationNonEmployeeService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private MultiTenantSendMessageProducer multiTenantSendMessageProducer;
    @Autowired
    private IOrganizationEmployeeService organizationEmployeeService;
    @Autowired
    private UserCacheManager userCacheManager;
    @Autowired
    private ICacheHandler cacheHandler;
    @Autowired
    private FreshPassengerRelationServiceImpl freshPassengerRelationService;
    @Autowired
    private TokenValidUtil tokenValidUtil;
    @Autowired
    private RoleService roleService;
    @Autowired
    private MbOrgEmployeeLoader mbOrgEmployeeLoader;
    @Autowired
    private ICostCenterService iCostCenterService;
    @Autowired
    private ExcelUtils excelUtils;
    @Autowired
    private ApprovalClientLoader approvalClientLoader;
    @Autowired
    private EventCenter eventCenter;
    @Autowired
    private RoleResourceManager roleResourceManager;
    @Autowired
    @Qualifier(value = "defaultThreadPoolExecutor")
    private ThreadPoolExecutor defaultThreadPoolExecutor;
    @Autowired
    private RedemptionCodeService redemptionCodeService;
    @Autowired
    private OrganizationApollo organizationApollo;
    @Autowired
    private MbUserOrgRelationMapper userOrgRelationMapper;
    @Autowired
    private IUserOrgRelationService iUserOrgRelationService;
    @Resource
    private EmployeeJobRelationMapper employeeJobRelationMapper;
    @Resource
    private TransactionTemplate transactionTemplate;
    @Resource
    private JobMapper jobMapper;

    private final static String COMPANY_DEPT_DESC_TEMP = "[{0}]-[{1}]";
    private final static String COMPANY_DESC_TEMP = "[{0}]";

    /**
     * 证件号掩码加密
     *
     * @param cardNo   证件号
     * @param cardType 证件类型
     * @return
     */
    private static String encryptCardNo(String cardNo, Integer cardType) {
        if (cardType == null || StrUtil.isEmpty(cardNo)) {
            return null;
        }
        if (cardType.equals(CardTypeEnum.ID_CARD.getCode())) {
            return idMask(cardNo, 4, 3);
        }
        if (cardNo.length() < 3) {
            return cardNo;
        }
        return idMask(cardNo, new BigDecimal(cardNo.length()).divide(new BigDecimal(3), 0, BigDecimal.ROUND_HALF_UP).intValue(), 2);
    }

    /**
     * 用户身份证号码的打码隐藏加星号加*
     * <p>18位和非18位身份证处理均可成功处理</p>
     * <p>参数异常直接返回null</p>
     *
     * @param idCardNum 身份证号码
     * @param front     需要显示前几位
     * @param end       需要显示末几位
     * @return 处理完成的身份证
     */
    public static String idMask(String idCardNum, int front, int end) {
        //身份证不能为空
        if (TextUtils.isEmpty(idCardNum)) {
            return null;
        }
        //需要截取的长度不能大于身份证号长度
        if ((front + end) > idCardNum.length()) {
            return null;
        }
        //需要截取的不能小于0
        if (front < 0 || end < 0) {
            return null;
        }
        //计算*的数量
        int asteriskCount = idCardNum.length() - (front + end);
        StringBuffer asteriskStr = new StringBuffer();
        for (int i = 0; i < asteriskCount; i++) {
            asteriskStr.append("*");
        }
        String regex = "(\\w{" + String.valueOf(front) + "})(\\w+)(\\w{" + String.valueOf(end) + "})";
        return idCardNum.replaceAll(regex, "$1" + asteriskStr + "$3");
    }

    @RequestMapping("/testKey")
    public void test() {
        System.out.println("key:" + 1000);
    }


    /**
     * 根据UID查询员工信息
     *
     * @param ids
     * @return
     */
    @PostMapping("/findEmployeeInfoByIds")
    public JSONResult<List<EmployeeOrgVo>> findEmployeeInfoByIds(@RequestBody List<String> ids) {
        List<EmployeeOrgVo> EmployeeOrgVo = organizationEmployeeService.findEmployeeInfoByIds(ids);
        return JSONResult.success(EmployeeOrgVo);
    }

    /**
     * 查询员工信息
     */
    @PostMapping("/queryEmployeeList")
    public JSONResult<QueryEmployeeResponse> queryEmployeeList(@RequestBody QueryEmployeeRequest request) {
        return JSONResult.success(organizationEmployeeService.queryEmployeeList(request));
    }

    /**
     * 组织架构/岗位—新增管理员员工初始化
     *
     * @param listEmployeeInAdminRequest
     * @return JSONResult
     */
    @RequestMapping("/ListEmployeeInAdmin")
    public JSONResult<ListEmployeeInAdminResponse> ListEmployeeInAdmin(@RequestBody @Valid ListEmployeeInAdminRequest listEmployeeInAdminRequest) {
        String orgId = listEmployeeInAdminRequest.getOrgId();
        String name = listEmployeeInAdminRequest.getStaffName();
        Integer pageNum = listEmployeeInAdminRequest.getIndex();
        Integer pageSize = listEmployeeInAdminRequest.getPageSize();
        ListEmployeeInAdminResponse listEmployeeInAdminResponse = new ListEmployeeInAdminResponse();
        List<String> allChildOrgIds = CollUtil.newArrayList(orgId);
        // 查询组织信息
        MbOrgInfo orgInfo = organizationInfoService.findByOrgId(orgId);
        // 1、	当前组织为部门，设置管理员时，展示并可选当前部门下所有在职员工（不穿透任何节点）。
        // 2、	当前组织为公司，设置管理员时，展示并可选当前公司及下属所有部门（不含子公司）的所有在职员工；提交时，在公司节点添加该员工的身份（需判重），并在公司节点的身份设置管理员。
        if (orgInfo.getOrgType().equals(OrganizationConst.COMPANY)) {
            // 通过orgId找到org下所有orgId
            allChildOrgIds = organizationInfoService.listAllDepartmentByOrgId(orgId);
        }
        // 通过组织结构id查询出员工信息列表
        List<MbOrgEmployeeInfo> employeeInfoList = organizationEmployeeService.listByNameAndOrgIds(name, allChildOrgIds, UserOrgRelationStatusEnum.NORMAL.getStatus(), pageNum, pageSize);
        if (CollectionUtils.isEmpty(employeeInfoList)) {
            // 没有查到员工信息返回空数组
            listEmployeeInAdminResponse.setStaffList(CollUtil.newArrayList());
            return new JSONResult<>(listEmployeeInAdminResponse);
        }
        List<OrgEmployeeVo> employeeList = CollUtil.newArrayList();
        // 组装数据
        for (MbOrgEmployeeInfo mbOrgEmployeeInfo : employeeInfoList) {
            OrgEmployeeVo orgEmployeeVo = new OrgEmployeeVo();
            orgEmployeeVo.setUid(mbOrgEmployeeInfo.getUid());
            orgEmployeeVo.setName(mbOrgEmployeeInfo.getName());
            orgEmployeeVo.setMobilePhone(mbOrgEmployeeInfo.getMobilePhone());
            orgEmployeeVo.setEmail(mbOrgEmployeeInfo.getEmail());
            orgEmployeeVo.setIsLeader(mbOrgEmployeeInfo.getIsLeader());
            employeeList.add(orgEmployeeVo);
        }
        PageInfo<MbOrgEmployeeInfo> page = new PageInfo<>(employeeInfoList);
        listEmployeeInAdminResponse.setCount(page.getTotal());
        listEmployeeInAdminResponse.setStaffList(employeeList);
        return new JSONResult<>(listEmployeeInAdminResponse);
    }

    public String getTreeParentId(Map<String, MbOrgInfo> orgIdMap, String orgId) {
        MbOrgInfo mbOrgInfo = orgIdMap.get(orgId);
        if (StringUtils.equals(mbOrgInfo.getOrgType(), OrgTypeEnum.C.getCode(), false)) {
            return mbOrgInfo.getOrgId();
        }
        return getTreeParentId(orgIdMap, mbOrgInfo.getParentId());
    }

    /**
     * 组织架构/岗位—人员信息列表
     *
     * @param listEmployeeInOrgRequest
     * @return JSONResult
     */
    @RequestMapping("/ListEmployeeInOrg")
    public JSONResult<ListEmployeeInOrgResponse> listEmployeeInOrg(@RequestBody @Valid ListEmployeeInOrgRequest listEmployeeInOrgRequest) {
        String orgId = listEmployeeInOrgRequest.getOrgId();

        List<String> orgIdDataPermissions = (List<String>) RequestContext.getCurrentContext().getContextParams(DATA_PERMISSION_ORG_ID_LIST);

        // 校验数据权限
        if(CollectionUtils.isNotEmpty(orgIdDataPermissions) && !orgIdDataPermissions.contains(orgId)){
            throw new CorpBusinessException(OrganizationResponseCodeEnum.DATA_OPERATION_NO_PERMISSION);
        }
        String condition = listEmployeeInOrgRequest.getStaffInfo();
        Integer pageNum = listEmployeeInOrgRequest.getIndex();
        Integer pageSize = listEmployeeInOrgRequest.getPageSize();

        ListEmployeeInOrgVO listEmployeeInOrgVO = new ListEmployeeInOrgVO();
        listEmployeeInOrgVO.setOrgId(orgId);
        listEmployeeInOrgVO.setStaffInfo(condition);
        listEmployeeInOrgVO.setIndex(pageNum);
        listEmployeeInOrgVO.setPageSize(pageSize);
        listEmployeeInOrgVO.setJobId(listEmployeeInOrgRequest.getJobId());


        ListEmployeeInOrgResponse listEmployeeInOrgResponse = new ListEmployeeInOrgResponse();
        Pair< List<MbOrgEmployeeInfo>,Long> res = organizationInfoService.listEmployeeInOrg(listEmployeeInOrgVO);
        List<MbOrgEmployeeInfo> employeeInfoList = res.getLeft();
        Long count = res.getRight();
        log.info("查询出得员工数据:{}", JsonUtils.toJsonString(employeeInfoList));
        // 通过组织结构id查询出员工信息列表

        MbOrgInfo mbOrgInfo = organizationInfoService.findByOrgId(orgId);
        if (CollectionUtils.isEmpty(employeeInfoList)) {
            listEmployeeInOrgResponse.setEmployeeList(CollUtil.newArrayList());
            listEmployeeInOrgResponse.setEnableStatus(mbOrgInfo != null && mbOrgInfo.getValid().equals(CommonConst.TRUE) ? 1 : 0);
            return new JSONResult<>(listEmployeeInOrgResponse);
        }

        List<MbOrgInfo> mbOrgInfoAll = organizationInfoService.listAll();

        Map<String, MbOrgInfo> orgInfoMap = mbOrgInfoAll.stream().collect(Collectors.toMap(MbOrgInfo::getOrgId, p -> p));
        // 查询员工岗位信息
        Map<String, EmployeeJobRelationDo> employeeJobRelationDoMap = employeeJobRelationMapper.listAll().stream().collect(Collectors.toMap(EmployeeJobRelationDo::getUid, item -> item, (k1, k2) -> k1));
        // 查询岗位信息
        Map<Long, JobDo> jobDoMap = jobMapper.listAll().stream().collect(Collectors.toMap(JobDo::getId, item -> item, (k1, k2) -> k1));
        // 查询人的证件信息
        List<String> uids = employeeInfoList.stream().map(MbOrgEmployeeInfo::getUid).collect(Collectors.toList());
        List<MbOrgUserIdcard> userIdcards = organizationUserIdCardService.batchFindByUids(uids);
        Map<String, List<MbOrgUserIdcard>> userCardMap = MapUtil.newHashMap();
        if (CollUtil.isNotEmpty(userIdcards)) {
            userCardMap = userIdcards.stream().sorted((a, b) -> b.getDatachangeLasttime().compareTo(a.getDatachangeLasttime())).collect(Collectors.groupingBy(MbOrgUserIdcard::getEmployeeUid));
        }
        List<OrgEmployeeVo> employeeList = CollUtil.newArrayList();
        // 循环封装数据
        for (MbOrgEmployeeInfo mbOrgEmployeeInfo : employeeInfoList) {
            OrgEmployeeVo orgEmployeeVo = new OrgEmployeeVo();
            orgEmployeeVo.setUid(mbOrgEmployeeInfo.getUid());
            orgEmployeeVo.setName(mbOrgEmployeeInfo.getName());
            orgEmployeeVo.setMobilePhone(mbOrgEmployeeInfo.getMobilePhone());
            orgEmployeeVo.setAreaCode(mbOrgEmployeeInfo.getAreaCode());
            orgEmployeeVo.setCreditCardNumbers(mbOrgEmployeeInfo.getCreditCardNumbers());
            List<MbOrgUserIdcard> idcards = userCardMap.get(mbOrgEmployeeInfo.getUid());
            List<GetUserInfoResponse.CardInfo> cardInfoList = new ArrayList<>();
            if (CollUtil.isNotEmpty(idcards)) {
                GetUserInfoResponse.CardInfo cardInfoVo = null;
                for (MbOrgUserIdcard mbOrgUserIdcard : idcards) {
                    cardInfoVo = new GetUserInfoResponse.CardInfo();
                    orgEmployeeVo.setCardType(mbOrgUserIdcard.getCardType());
                    // 证件号加密
                    String encryptStr = encryptCardNo(mbOrgUserIdcard.getCardNo(), mbOrgUserIdcard.getCardType());
                    orgEmployeeVo.setCardNo(encryptStr);
                    cardInfoVo.setCardType(mbOrgUserIdcard.getCardType());
                    cardInfoVo.setCardNo(encryptStr);
                    cardInfoList.add(cardInfoVo);
                }
                orgEmployeeVo.setCardList(cardInfoList);
            }

            List<MbRole> roleInfos = roleService.findByUidAndOrgId(mbOrgEmployeeInfo.getUid(), mbOrgEmployeeInfo.getOrgId());

            if (CollectionUtils.isNotEmpty(roleInfos)) {

                //目前应该没有多角色情况 应该只有一条
                for (MbRole role : roleInfos) {
                    orgEmployeeVo.setRoleInfo(Lists.newArrayList(role.getName()));
                    orgEmployeeVo.setRoleId(role.getId());
                }

            }
            orgEmployeeVo.setIsLeader(mbOrgEmployeeInfo.getIsLeader() != null && mbOrgEmployeeInfo.getIsLeader());
            orgEmployeeVo.setStatus(mbOrgEmployeeInfo.getStatus());
            // 职级
            Long postId = mbOrgEmployeeInfo.getPostId();
            if (postId != null) {
                MbPostInfo mbPostInfo = postService.find(postId);
                orgEmployeeVo.setRank(mbPostInfo.getName());
            }
            orgEmployeeVo.setOrgId(mbOrgEmployeeInfo.getOrgId());
            orgEmployeeVo.setCorpId(getTreeParentId(orgInfoMap, mbOrgEmployeeInfo.getOrgId()));

            orgEmployeeVo.setPostId(mbOrgEmployeeInfo.getPostId());
            if (StringUtils.isNotBlank(condition)) {
                List<OrgInfoVo> orgInfoList = organizationInfoService.getOrgInfoList(orgEmployeeVo.getOrgId(), true);
                List<String> returnList = new ArrayList<>();
                if (CollectionUtils.isNotEmpty(orgInfoList)) {
                    returnList = orgInfoList.stream().sorted(Comparator.comparing(OrgInfoVo::getLevel))
                            .map(OrgInfoVo::getName).collect(Collectors.toList());
                    StringBuilder buffer = new StringBuilder();
                    for (String orgName : returnList) {
                        buffer.append(orgName).append(">");
                    }
                    orgEmployeeVo.setOrgNames(buffer.substring(0, buffer.length() - 1));
                }

            }
            orgEmployeeVo.setEmployeeType(mbOrgEmployeeInfo.getEmployeeType());
            orgEmployeeVo.setEmployeeDesc(ApplyTripEmployeeEnum.getNameByCode(mbOrgEmployeeInfo.getEmployeeType()));
            // 员工岗位信息
            Optional.ofNullable(employeeJobRelationDoMap.get(mbOrgEmployeeInfo.getUid())).map(employeeJobRelationDo -> jobDoMap.get(employeeJobRelationDo.getJobId())).ifPresent(jobDo -> {
                orgEmployeeVo.setJobId(jobDo.getId());
                orgEmployeeVo.setJobName(jobDo.getName());
                orgEmployeeVo.setJobCode(jobDo.getCode());
            });
            employeeList.add(orgEmployeeVo);
        }
        PageInfo<MbOrgEmployeeInfo> page = new PageInfo<>(employeeInfoList);
        listEmployeeInOrgResponse.setCount(count);
        listEmployeeInOrgResponse.setEmployeeList(employeeList);
        if (mbOrgInfo != null) {
            listEmployeeInOrgResponse.setBindOrgName(mbOrgInfo.getBindName());
            listEmployeeInOrgResponse.setEnableStatus(mbOrgInfo.getValid().equals(CommonConst.TRUE) ? 1 : 0);
        }
        return new JSONResult<>(listEmployeeInOrgResponse);
    }

    private void getOrgIds(List<GetOrgTreeResponse> list, List<String> orgIds) {
        if (!CollectionUtils.isEmpty(list)) {
            for (GetOrgTreeResponse temp : list) {
                orgIds.add(temp.getOrgId());
                if (!CollectionUtils.isEmpty(temp.getChildren())) {
                    getOrgIds(temp.getChildren(), orgIds);
                }
            }
        }
    }


    @RequestMapping("/employeeInOrgDownload")
    public void download(@RequestBody @Valid ListEmployeeInOrgRequest listEmployeeInOrgRequest, HttpServletResponse response) {
        String orgId = listEmployeeInOrgRequest.getOrgId();
        String condition = listEmployeeInOrgRequest.getStaffInfo();
        List<MbOrgEmployeeInfo> employeeInfoList = CollUtil.newArrayList();
        ListEmployeeQuery listEmployeeQuery = new ListEmployeeQuery();

        if (StrUtil.isNotBlank(condition)) {
            //查询组织
            BaseUserInfo baseUserInfo = userCacheManager.getBaseUserInfo();
            boolean ifShowChildCompany = true;
            boolean ifStartWithCompany = true;
            // 查询所有组织结构
            List<MbOrgInfo> mbOrgInfoList = organizationInfoService.listAll();
            // #1.后台用户，查询所有组织结构
            List<GetOrgTreeResponse> getOrgTreeResponses = null;
            if (baseUserInfo.getBgUser()) {
                getOrgTreeResponses = OrganizationUtil.listOrgTree(mbOrgInfoList, null, ifShowChildCompany);
            } else {
                String queryOrgId = null;
                // #2.不是后台用户
                // #2.1需要从最近公司开始展示树
                if (ifStartWithCompany) {
                    queryOrgId = baseUserInfo.getCorpId();
                } else {
                    // #2.2不需要从最近公司开始展示树
                    queryOrgId = baseUserInfo.getOrgId();
                }
                getOrgTreeResponses = OrganizationUtil.listOrgTree(mbOrgInfoList, queryOrgId, ifShowChildCompany);
            }
            List<String> orgIds = new ArrayList<>();
            //查询有权限公司id
            getOrgIds(getOrgTreeResponses, orgIds);
            listEmployeeQuery.setQuery(condition);
            employeeInfoList = userOrgRelationService.listByQueryAndOgrIds(listEmployeeQuery, orgIds, listEmployeeInOrgRequest.getRoleId());
        } else {
            listEmployeeQuery.setOrgId(orgId);
            employeeInfoList = userOrgRelationService.listByQuery(listEmployeeQuery, listEmployeeInOrgRequest.getRoleId());
        }

        if (CollectionUtils.isEmpty(employeeInfoList)) {
            return;
        }

        //获取职级信息id
        List<Long> postId = employeeInfoList.stream().map(MbOrgEmployeeInfo::getPostId).collect(Collectors.toList());
        //获取角色信息
        List<String> uids = employeeInfoList.stream().map(MbOrgEmployeeInfo::getUid).collect(Collectors.toList());

        Map<Long, MbPostInfo> postInfoMap = postService.listByPostIds(postId).stream().collect(Collectors.toMap(MbPostInfo::getId, item -> item));

        List<UserRole> userRole = Optional.ofNullable(userRoleService.listRole(Lists.newArrayList(orgId))).orElse(Lists.newArrayList()).stream().filter(i -> uids.contains(i.getUserId())).collect(Collectors.toList());

        Map<String, List<UserRole>> userRoleMap = userRole.stream().collect(Collectors.groupingBy(UserRole::getUserId));

        Map<Long, List<MbRole>> roleMap = roleService.selectRoles(userRole.stream().map(UserRole::getRoleId).collect(Collectors.toList())).stream().collect(Collectors.groupingBy(MbRole::getId));

        MbOrgInfo mbOrgInfo = organizationInfoService.findByOrgId(orgId);

        MbOrgInfo corpInfo = new MbOrgInfo();

        if (!Objects.equals(mbOrgInfo.getOrgType(), OrgTypeEnum.D.getCode()) && !Objects.equals(mbOrgInfo.getOrgType(), OrgTypeEnum.G.getCode())) {
            corpInfo = organizationInfoService.findFirstCorpInfo(orgId);
        }

        List<CostCenter> costCenters = iCostCenterService.getCostCenter(orgId);

        MbOrgInfo finalCorpInfo = corpInfo;
        List<EmployeeInfoListExcelVO> employeeInfoListExcelVOS = employeeInfoList.stream().map(bean -> {
            EmployeeInfoListExcelVO employeeInfoListExcelVO = new EmployeeInfoListExcelVO();
            employeeInfoListExcelVO.setUid(bean.getUid());
            employeeInfoListExcelVO.setUName(bean.getName());
            employeeInfoListExcelVO.setBirthday(DateUtil.format(bean.getBirthday(), DatePattern.NORM_DATETIME_PATTERN));
            employeeInfoListExcelVO.setCorpName(Objects.equals(OrgTypeEnum.D.getCode(), mbOrgInfo.getOrgType()) ? mbOrgInfo.getName() : finalCorpInfo.getName());
            employeeInfoListExcelVO.setDepName(mbOrgInfo.getName());
            employeeInfoListExcelVO.setEmail(bean.getEmail());
            employeeInfoListExcelVO.setFirstEnName(bean.getFirstEnName());
            employeeInfoListExcelVO.setEnName(bean.getLastEnName());
            employeeInfoListExcelVO.setPhone(bean.getMobilePhone());
            employeeInfoListExcelVO.setPostName(postInfoMap.get(postId) == null ? null : postInfoMap.get(postId).getName());
            List<UserRole> userRoles = userRoleMap.get(bean.getUid());
            if (!CollectionUtils.isEmpty(userRoles)) {
                employeeInfoListExcelVO.setRoleName(roleMap.get(userRole.get(0)).get(0).getName());
            }
            employeeInfoListExcelVO.setSex(Objects.isNull(bean.getGender()) ? null : Objects.equals("M", bean.getGender()) ? "男" : "女");
            if (CollectionUtils.isNotEmpty(costCenters)){
                employeeInfoListExcelVO.setCostCenterName(costCenters.stream().map(CostCenter::getCostCenterName).collect(Collectors.joining(",")));
            }
            return employeeInfoListExcelVO;
        }).collect(Collectors.toList());

        //报表下载
        ExcelCreateVO<EmployeeInfoListExcelVO> vo = ExcelCreateVO.<EmployeeInfoListExcelVO>builder()
                .fileName("组织人员")
                .dataList(employeeInfoListExcelVOS)
                .postfix(ExcelPostEnum.xlsx)
                .cls(EmployeeInfoListExcelVO.class)
                .build();
        excelUtils.downloadExcelDocument(response, vo);
    }

    /**
     * 组织架构/岗位—人员信息列表_删除员工
     *
     * @param deleteUserOrgRelationRequest
     * @return
     */
    @RequestMapping("/deleteRelation")
    public JSONResult<Boolean> deleteRelation(@RequestBody @Valid DeleteUserOrgRelationRequest deleteUserOrgRelationRequest) {
        try {
            deleteUserOrgRelationRequest.setUids(Collections.singletonList(deleteUserOrgRelationRequest.getUid()));
            deleteAllByUid(deleteUserOrgRelationRequest);
        } catch (Exception e){
            return new JSONResult<>(Boolean.FALSE);
        }

        return new JSONResult<>(Boolean.TRUE);
    }

    /**
     * 根据UID 删除用户相关的信息
     *
     * @param deleteUserOrgRelationRequest
     * @return
     */
    @PostMapping("/deleteAllByUid")
    public JSONResult<Map<String, Object>> deleteAllByUid(@RequestBody DeleteUserOrgRelationRequest deleteUserOrgRelationRequest) {
        if (CollectionUtils.isEmpty(deleteUserOrgRelationRequest.getUids())) {
            deleteUserOrgRelationRequest.setUids(new ArrayList<>());
        }
        log.info("DeleteUserOrgRelationRequest:{}", JsonUtils.toJsonString(deleteUserOrgRelationRequest));
        List<Future<Boolean>> allTask = deleteUserOrgRelationRequest.getUids().stream()
                .map(uid -> defaultThreadPoolExecutor.submit(() -> userOrgRelationService.deleteAllByUid(uid, deleteUserOrgRelationRequest.getOrgId())))
            .collect(Collectors.toList());
        AsyncTaskUtil.getAllResult(allTask, 20, TimeUnit.SECONDS);
        //暂无业务上的删除校验
        Map<String, Object> map = new HashMap<>();
        map.put("count", deleteUserOrgRelationRequest.uids.size());
        map.put("successNum", deleteUserOrgRelationRequest.uids.size());
        map.put("failNum", 0);
        return JSONResult.success(map);
    }

    /**
     * 根据ogrId 删除用户相关的信息
     */
    @PostMapping("/deleteAllByOrgId")
    public JSONResult<DeleteUserOrgRelationByOrgIdResponse> deleteAllByOrgId(@RequestBody DeleteUserOrgRelationByOrgIdRequest request) {
        if (CollectionUtils.isEmpty(request.getOrgIds())){
            return buildDeleteUserOrgRelationByOrgIdResponse(0, 0, 0, Collections.emptyList());
        }
        // 根据组织id查询出所有员工
        List<SearchCorpEmpResponse> employees = organizationEmployeeService.selectEmployeeByOrgIds(request.getOrgIds());
        if (CollectionUtils.isEmpty(request.getOrgIds())){
            return buildDeleteUserOrgRelationByOrgIdResponse(0, 0, 0, Collections.emptyList());
        }
        Map<String, String> corpEmpResponseMap = employees.stream().collect(Collectors.toMap(SearchCorpEmpResponse::getUid,SearchCorpEmpResponse::getOrgId, (t1, t2) -> t2));
        // 根据查询出的员工uid删除员工信息
        List<Future<String>> allTask = employees.stream().map(SearchCorpEmpResponse::getUid)
                .filter(StringUtils::isNotBlank).distinct()
                .map(uid -> defaultThreadPoolExecutor.submit(() -> userOrgRelationService.deleteAllByUid(uid, corpEmpResponseMap.get(uid)) ? uid : null))
                .collect(Collectors.toList());

        // 获取成功删除的uid
        Set<String> successUid = new HashSet<>(AsyncTaskUtil.getAllResult(allTask, 10, TimeUnit.SECONDS));
        successUid.removeIf(Objects::isNull);

        // 获取删除成功总数
        Set<String> totalUidSet = employees.stream().map(SearchCorpEmpResponse::getUid).collect(Collectors.toSet());
        int successCount = (int) totalUidSet.stream().map(successUid::contains).filter(x -> x).count();
        int failCount = totalUidSet.size() - successCount;
        // 获取每个orgId下的uid删除结果
        List<DeleteUserOrgRelationByOrgIdResultInfo> resultDetail = new ArrayList<>();
        employees.stream().collect(Collectors.groupingBy(SearchCorpEmpResponse::getOrgId, Collectors.mapping(SearchCorpEmpResponse::getUid, Collectors.toSet())))
                .forEach((orgId, uidSet) -> resultDetail.add(buildDeleteUserOrgRelationByOrgIdResult(orgId, uidSet, successUid)));

        // 构建结果返回
        return buildDeleteUserOrgRelationByOrgIdResponse(totalUidSet.size(), successCount, failCount, resultDetail);
    }

    private  JSONResult<DeleteUserOrgRelationByOrgIdResponse> buildDeleteUserOrgRelationByOrgIdResponse(int totalSize, int successCount, int failCount, List<DeleteUserOrgRelationByOrgIdResultInfo> resultDetail) {
        DeleteUserOrgRelationByOrgIdResponse response = new DeleteUserOrgRelationByOrgIdResponse();
        response.setTotalCount(totalSize);
        response.setSuccessCount(successCount);
        response.setFailCount(failCount);
        response.setDeleteResultDetail(resultDetail);
        return JSONResult.success(response);
    }

    /**
     * 构建删除用户相关信息结果明细
     *
     * @param orgId  组织id
     * @param uidSet 此组织id下的uid集合
     * @param successUidSet 删除成功的uid集合
     */
    DeleteUserOrgRelationByOrgIdResultInfo buildDeleteUserOrgRelationByOrgIdResult(String orgId, Set<String> uidSet, Set<String> successUidSet) {
        DeleteUserOrgRelationByOrgIdResultInfo result = new DeleteUserOrgRelationByOrgIdResultInfo();
        result.setOrgId(orgId);
        result.setTotalCount(uidSet.size());
        int successCount = (int) uidSet.stream().map(successUidSet::contains).filter(x -> x).count();
        result.setSuccessCount(successCount);
        result.setFailCount(uidSet.size() - successCount);
        return result;
    }


    /**
     * 组织架构/岗位—人员信息列表_修改员工状态
     * 0拒绝 1同意  2离职  3恢复
     *
     * @param updateUserOrgRelationRequest
     * @return
     */
    @RequestMapping("/updateRelationStatus")
    @Transactional(rollbackFor = Exception.class)
    public JSONResult<Boolean> updateRelationStatus(@RequestBody @Valid UpdateUserOrgRelationRequest updateUserOrgRelationRequest) {
        List<String> id = updateUserOrgRelationRequest.getId();
        String orgId = updateUserOrgRelationRequest.getOrgId();
        Integer type = updateUserOrgRelationRequest.getType();
        if (type == 2) {
            type = UserOrgRelationStatusEnum.LEAVE.getStatus();
        } else if (type == 3) {
            type = UserOrgRelationStatusEnum.NORMAL.getStatus();
        }
        boolean flag = userOrgRelationService.batchUpdateStatus(id, orgId, type);
        // 将身份设为离职后：清除该身份的管理员信息、清除该身份的负责人标志。
        if (updateUserOrgRelationRequest.getType() == 2) {
            // 清除管理员
            boolean result = userOrgRelationService.batchClearLeader(id, orgId);
            BatchUpdateRole4UserReq req = new BatchUpdateRole4UserReq();
            req.setUids(id);
            req.setOrgId(orgId);
            // 清除管理员
            try {
                Set<UidOrgIdEntry> ids = new HashSet<>();
                UidOrgIdEntry uidOrgIdEntry = null;
                for (String idtemp : id) {
                    uidOrgIdEntry = new UidOrgIdEntry();
                    uidOrgIdEntry.setUid(idtemp);
                    uidOrgIdEntry.setOrgId(orgId);
                    ids.add(uidOrgIdEntry);
                }
                userRoleService.clearLeft(ids);
            } catch (Exception e) {
                e.printStackTrace();
            }
            // 将出行人表数据置位禁用
            boolean flagB = freshPassengerService.batchInvalid(id, orgId);

            for (String str : id) {
                tokenValidUtil.updateUserOrgTokenValid(str, orgId, false);
            }
            log.info("出行人数据禁用[{}]", flagB);
        }
        // 如果恢复身份，需要恢复用户的出行人信息
        if (updateUserOrgRelationRequest.getType() == 3 || updateUserOrgRelationRequest.getType() == 1) {
            // 将出行人表数据置位禁用
            boolean flagB = freshPassengerService.batchValid(id, orgId);
            log.info("出行人数据恢复[{}]", flagB);
        }
        if (updateUserOrgRelationRequest.getType() == 3 || updateUserOrgRelationRequest.getType() == 1) {
            for (String str : id) {
                tokenValidUtil.updateUserOrgTokenValid(str, orgId, true);
            }
        }
        // # 发短信
        if (updateUserOrgRelationRequest.getType() == 1 || updateUserOrgRelationRequest.getType() == 2) {
            // 查询员工信息
            List<MbOrgEmployeeInfo> list = organizationEmployeeService.listByUids(id);
            // 查询部门信息
            List<MbOrgInfo> mbOrgInfoList = organizationInfoService.listAll();
            Map<String, MbOrgInfo> mbOrgInfoMap = mbOrgInfoList.stream().collect(Collectors.toMap(MbOrgInfo::getOrgId, p -> p));
            for (MbOrgEmployeeInfo mbOrgEmployeeInfo : list) {
                // 最近子公司信息
                MbOrgInfo recentCompanyInfo = OrganizationUtil.findRecentCompanyInfo(orgId, mbOrgInfoMap);
                // 部门信息
                MbOrgInfo mbOrgInfo = mbOrgInfoMap.get(orgId);
                String orgDesc = "";
                if (Objects.equals(orgId, recentCompanyInfo.getOrgId())) {
                    orgDesc = MessageFormat.format(COMPANY_DESC_TEMP, mbOrgInfo.getName());
                } else {
                    orgDesc = MessageFormat.format(COMPANY_DEPT_DESC_TEMP, recentCompanyInfo.getName(), mbOrgInfo.getName());
                }
                String finalOrgDesc = orgDesc;
                CompletableFuture.runAsync(() -> multiTenantSendMessageProducer.sendMsg(toApproveUserMessage(updateUserOrgRelationRequest.getType(), mbOrgEmployeeInfo.getAreaCode(), mbOrgEmployeeInfo.getMobilePhone(), ImmutableMap.of("orgDesc", finalOrgDesc))), defaultThreadPoolExecutor);
            }
        }
        return new JSONResult<>(flag);
    }

    private MessageVo toApproveUserMessage(int type, String countryCode, String phoneNum, Map<String, Object> vars) {
        MessageVo messageVo = new MessageVo();
        MessageVo.Sms sms = new MessageVo.Sms();
        sms.setBizType(type == 1 ? MsgBizType.EMPLOYEE_APPROVAL_PASS : MsgBizType.EMPLOYEE_APPROVAL_REJECT);
        sms.setCountryCode(countryCode);
        sms.setPhone(phoneNum);
        sms.setVars(vars);
        messageVo.setSms(sms);
        return messageVo;
    }

//    /**
//     * 通过组织结构id找到部门下所有员工信息，分页(分页，排序按照 leader，sleader，vip排序，之后按照创建时间正序)，再分别查出部门负责人，次级负责人，员工总数
//     * 前端接口
//     * 契约文档地址：http://10.5.119.87:9526/project/11/interface/api/167
//     * 本地访问地址：http://localhost:7890/employee/getDepartmentInfo?orgId=1&page=1
//     *
//     * @param request id,page
//     * @return JSONResult
//     */
//    @RequestMapping("/getDepartmentInfo")
//    @ResponseBody
//    public JSONResult<DepartmentAndEmployeeListVo> getDepartmentInfo(@RequestBody GetDepartmentInfoRequest request, HttpServletRequest httpRequest) {
//        String uid = httpRequest.getParameter("uId");
//        String userName = httpRequest.getParameter("userName");
//
//
//        String id = request.getId();
//        Integer page = request.getPage();
//        if (StringUtils.isBlank(id)) {
//            return JSONResult.errorMsg("orgId参数缺失");
//        }
//        // 返回的VO
//        DepartmentAndEmployeeListVo returnVo = new DepartmentAndEmployeeListVo();
//        returnVo.setEmployeeList(Collections.emptyList());
//        // 获取组织信息
//        MbOrgInfo mbOrgInfo = organizationInfoService.findByOrgId(id);
//        if (mbOrgInfo == null) {
//            throw new CorpBusinessException(ExceptionCodeEnum.Alert, "不存在的组织架构");
//        }
//        String orgType = mbOrgInfo.getOrgType();
//        returnVo.setType(mbOrgInfo.getOrgType());
//        returnVo.setName(mbOrgInfo.getName());
//        returnVo.setId(id);
//        // 如果查询是部门，需要获取部门的负责人和次级负责人
//        if (OrganizationConst.DEPARTMENT.equals(orgType)) {
//        }
//        // 判断请求用户是否是前台员工
//        List<String> allChildOrgIds = new ArrayList<>();
//        boolean backgroundUser = organizationEmployeeService.isBackgroundUser(uid);
//        if (backgroundUser) {
//            // 通过orgId找到org下所有orgId
//            organizationInfoService.findAllChildOrgIdsByOrgId(id, allChildOrgIds);
//        } else {
//            allChildOrgIds = organizationInfoService.findDirectDepartmentChildOrgIdsByOrgId(id);
//        }
//
//
//        if (CollectionUtils.isEmpty(allChildOrgIds) && !OrganizationConst.DEPARTMENT.equals(orgType)) {
//            return new JSONResult<>(returnVo);
//        }
//        allChildOrgIds.add(id);
//        // 通过组织结构id查询出员工信息列表
//        List<MbOrgEmployeeInfo> employeeInfoList = organizationEmployeeService.batchFindAllByOrgIds(allChildOrgIds, page, CommonConst.PAGE_SIZE_10);
//        if (CollectionUtils.isEmpty(employeeInfoList)) {
//            return new JSONResult<>(returnVo);
//        }
//        // 筛选出所有组织架构id
//        List<String> orgIds = employeeInfoList.stream().map(MbOrgEmployeeInfo::getOrgId).collect(Collectors.toList());
//        // 查询出组织结构名称
//        List<MbOrgInfo> orgInfoList = organizationInfoService.listNameByOrgIds(orgIds);
//        // 转成map，之后组装返回数据
//        Map<String, String> orgNameMap = orgInfoList.stream().collect(Collectors.toMap(MbOrgInfo::getOrgId, MbOrgInfo::getName));
//
//        List<EmployeePageVo> employeeList = new ArrayList<>(10);
//        // 组装数据
//        for (MbOrgEmployeeInfo mbOrgEmployeeInfo : employeeInfoList) {
//            EmployeePageVo employeePageVo = new EmployeePageVo();
//            employeePageVo.setName(mbOrgEmployeeInfo.getName());
//            employeePageVo.setPhone(mbOrgEmployeeInfo.getMobilePhone());
//            if (MapUtils.isNotEmpty(orgNameMap)) {
//                employeePageVo.setDepartment(orgNameMap.get(mbOrgEmployeeInfo.getOrgId()));
//            }
//            employeePageVo.setId(mbOrgEmployeeInfo.getUid());
//            employeeList.add(employeePageVo);
//        }
//        returnVo.setEmployeeList(employeeList);
//        // todo 分页参数怎么返回
//        PageInfo<MbOrgEmployeeInfo> pageInfo = new PageInfo<>(employeeInfoList);
//        long total = pageInfo.getTotal();
//        returnVo.setAmount(total);
//        return JSONResult.success(returnVo);
//    }

    /**
     * {"name":'身份证',"value":'1'},
     * {"name":'护照',"value":'2'},
     * {"name":'学生证',"value":'3'},
     * {"name":'军人证',"value":'4'},
     * {"name":'回乡证',"value":'7'},
     * {"name":'台胞证',"value":'8'},
     * {"name":'港澳通行证',"value":'10'},
     * {"name":'旅行证',"value":'21'},
     * {"name":'台湾通行证',"value":'22'},
     * {"name":'其他',"value":'99'}
     *
     * @return
     */
    private List<CardType> getCardTypeList() {
        List<CardType> returnList = new ArrayList<>();
        returnList.add(CardType.builder().name("身份证").value("1").build());
        returnList.add(CardType.builder().name("护照").value("2").build());
        returnList.add(CardType.builder().name("学生证").value("3").build());
        returnList.add(CardType.builder().name("军人证").value("4").build());
        returnList.add(CardType.builder().name("回乡证").value("7").build());
        returnList.add(CardType.builder().name("台胞证").value("8").build());
        returnList.add(CardType.builder().name("港澳通行证").value("10").build());
        returnList.add(CardType.builder().name("旅行证").value("21").build());
        returnList.add(CardType.builder().name("台湾通行证").value("22").build());
        returnList.add(CardType.builder().name("其他").value("99").build());
        return returnList;
    }

    /**
     * 通过岗位id查询员工信息，创建时间正序。
     * 前端接口
     * 契约文档：http://10.5.119.87:9526/project/11/interface/api/566
     * url：http://localhost:7890/employee/listByPostId?postId=1&pageNum=1&pageSize=10
     *
     * @param request id,page
     * @return 员工列表 uid,name,orgId,orgName,role,roleName,valid
     */
    @RequestMapping("/getPositionInfo")
    @ResponseBody
    public JSONResult<PositionEmployeeListVo> getPositionInfo(@RequestBody GetPositionInfoRequest request,BaseUserInfo userInfo) {
        Long id = request.getId();
        Integer page = request.getPage();
        Integer size = request.getSize();
        PositionEmployeeListVo positionEmployeeListVo = new PositionEmployeeListVo();
        positionEmployeeListVo.setEmployeeList(new ArrayList<>());
        MbPostInfo mbPostInfo = new MbPostInfo();
        if (id != null) {
            // 查询岗位信息
            mbPostInfo = postService.find(id);
            if (Objects.isNull(mbPostInfo)) {
                return JSONResult.errorMsg("查询岗位信息为空");
            }
            positionEmployeeListVo.setName(mbPostInfo.getName());
            positionEmployeeListVo.setId(mbPostInfo.getId());
        }

        List<String> dataPermissionOrgIds=null;
        //非admin用户
        if(userInfo.getBgUser()!=null&&!userInfo.getBgUser()){
            dataPermissionOrgIds = (List<String>) RequestContext.getCurrentContext().getContextParams(DATA_PERMISSION_ORG_ID_LIST);
        }
        log.info("职级管理 userInfo:{},dataPermissionOrgIds:{}",JsonUtils.toJsonString(userInfo),JsonUtils.toJsonString(dataPermissionOrgIds));

        // #1.查询岗位下人员列表
        List<MbOrgEmployeeInfo> list;
        if (page == null) {
            list = organizationEmployeeService.listByPostIdOrUid(id, request.getUid());
        } else {
            list = organizationEmployeeService.listPageByPostIdOrUid(id, page, size == null ? CommonConst.PAGE_SIZE_10 : size, request.getUid(),dataPermissionOrgIds);
        }
        if (CollectionUtils.isEmpty(list)) {
            return JSONResult.success(positionEmployeeListVo);
        }
        //根据筛选框  选择条件进行返回
        if (StringUtils.isNotBlank(request.getUid())) {
            mbPostInfo = postService.find(list.get(0).getPostId());
            positionEmployeeListVo.setName(mbPostInfo.getName());
            positionEmployeeListVo.setId(mbPostInfo.getId());
        }

        log.info("员工信息:{}", JsonUtils.toJsonString(list));
        List<String> orgIds = list.stream().map(MbOrgEmployeeInfo::getOrgId).distinct().collect(Collectors.toList());
        // #2.查询组织结构名称
        List<MbOrgInfo> mbOrgInfoList = organizationInfoService.listNameByOrgIds(orgIds);
        if (CollectionUtils.isEmpty(mbOrgInfoList)) {
            return JSONResult.errorMsg("组织结构信息为空");
        }
        // key:orgId , value:name
        Map<String, String> orgNameMap = mbOrgInfoList.stream().collect(Collectors.toMap(MbOrgInfo::getOrgId, MbOrgInfo::getName));
        // 组装数据
        List<EmployeePageVo> employeeList = new ArrayList<>();
        for (MbOrgEmployeeInfo orgEmployeeVo : list) {
            EmployeePageVo employeePageVo = new EmployeePageVo();
            employeePageVo.setId(orgEmployeeVo.getUid());
            employeePageVo.setName(orgEmployeeVo.getName());
            employeePageVo.setDepartment(orgNameMap.get(orgEmployeeVo.getOrgId()));
            employeePageVo.setPhone(orgEmployeeVo.getMobilePhone());
            employeePageVo.setOrgId(orgEmployeeVo.getOrgId());
            if (mbPostInfo != null && mbPostInfo.getAllowance() != null) {
                employeePageVo.setAllowance(mbPostInfo.getAllowance().setScale(2, RoundingMode.HALF_UP).toString());
            }
            employeeList.add(employeePageVo);
        }
        positionEmployeeListVo.setEmployeeList(employeeList);
        PageInfo<MbOrgEmployeeInfo> listPage = new PageInfo<>(list);
        positionEmployeeListVo.setAmount(listPage.getTotal());
        return JSONResult.success(positionEmployeeListVo);
    }

    @RequestMapping("/getAllPositionInfo")
    @ResponseBody
    public JSONResult<PositionEmployeeListVo> getAllPositionInfo(@RequestBody GetPositionInfoRequest request,BaseUserInfo userInfo) {
        return getPositionInfo(request,userInfo);
    }

    /**
     * 通过部门id/岗位id查询部门下所有员工信息
     * 前端接口
     * 契约文档：http://10.5.119.87:9526/project/11/interface/api/566
     * url：http://localhost:7890/employee/getSelectedEmp
     *
     * @param request id（部门id）
     * @return 员工列表
     */
    @RequestMapping("/getSelectedEmp")
    @ResponseBody
    public JSONResult<List<DepartmentEmployeeVo>> getSelectedEmp(@RequestBody ListEmployeeRequest request) {
        List<DepartmentEmployeeVo> returnList = new ArrayList<>();
        // 左侧部门id
        String currentId = request.getId();
        // 组织架构类型（岗位：P 部门：D）
        String type = request.getType();
        List<MbOrgEmployeeInfo> list = new ArrayList<>();
        if (type.equals("D")) {
            // 查询部门下所有人
            list = organizationEmployeeService.listAllByDepartmentIdAndName(currentId, null);
        } else if (type.equals("P")) {
            list = organizationEmployeeService.listByPostId(Long.valueOf(currentId));
        }

        if (CollectionUtils.isEmpty(list)) {
            return new JSONResult<>(returnList);
        }
        List<String> orgIds = list.stream().map(MbOrgEmployeeInfo::getOrgId).distinct().collect(Collectors.toList());
        // 查询所有部门名称
        List<MbOrgInfo> nameList = organizationInfoService.listNameByOrgIds(orgIds);
        Map<String, String> nameMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(nameList)) {
            nameMap = nameList.stream().collect(Collectors.toMap(p -> p.getOrgId(), mbOrgInfo -> mbOrgInfo.getName()));
        }
        for (MbOrgEmployeeInfo mbOrgEmployeeInfo : list) {
            DepartmentEmployeeVo departmentEmployeeVo = new DepartmentEmployeeVo();
            departmentEmployeeVo.setId(mbOrgEmployeeInfo.getUid());
            departmentEmployeeVo.setLabel(mbOrgEmployeeInfo.getName());
            departmentEmployeeVo.setStatus(1);
            departmentEmployeeVo.setOrgId(mbOrgEmployeeInfo.getOrgId());
            if (MapUtils.isNotEmpty(nameMap)) {
                departmentEmployeeVo.setDepartment(nameMap.get(mbOrgEmployeeInfo.getOrgId()));
            }
            returnList.add(departmentEmployeeVo);
        }
        return new JSONResult<>(returnList);
    }

//    /**
//     * 姓名和员工编号模糊匹配
//     * 前端接口
//     * 契约文档：http://mdoc.uat.qa.nt.ctripcorp.com:9526/project/11/interface/api/836
//     * url：http://localhost:7890/employee/searchOrgEmp
//     *
//     * @param request
//     * @return 员工列表
//     */
//    @RequestMapping("/searchOrgEmp")
//    @ResponseBody
//    public JSONResult<SearchOrgEmpPageResponse> searchOrgEmp(@RequestBody SearchOrgEmpRequest request, HttpServletRequest httpRequest) {
//
//        String uid = httpRequest.getParameter("uId");
//        String userName = httpRequest.getParameter("userName");
//
//        // todo 根据uid判断用户权限，需要实现
//
//        // 根据uid判断权限
//        MbOrgEmployeeInfo backgroundUser = organizationEmployeeService.findByUid(uid);
//        List<String> departmentList = new ArrayList<>();
//        if (!backgroundUser.getIsBackground()) {
//            departmentList = organizationInfoService.listRecentCompanyDirectDepartmentByOrgId(backgroundUser.getOrgId());
//        }
//        String scope = request.getScope();
//        Integer page = request.getPage();
//        String query = request.getQuery();
//
//        SearchOrgEmpPageResponse searchOrgEmpPageResponse = new SearchOrgEmpPageResponse();
//
//        List<MbOrgEmployeeInfo> list = new ArrayList<>();
//        // 姓名维度
//        if (scope.equals("1")) {
//            if (!backgroundUser.getIsBackground() && CollectionUtils.isNotEmpty(departmentList)) {
//                list = organizationEmployeeService.listPageByOrgIdsAndName(departmentList, query, page, 10);
//            } else {
//                list = organizationEmployeeService.listByNamePage(query, page, 10);
//            }
//            if (CollectionUtils.isEmpty(list)) {
//                searchOrgEmpPageResponse.setEmployeeList(Collections.emptyList());
//                return new JSONResult<>(searchOrgEmpPageResponse);
//            }
//            // 员工编号
//        } else if (scope.equals("2")) {//手机号码
//            if (!backgroundUser.getIsBackground() && CollectionUtils.isNotEmpty(departmentList)) {
//                list = organizationEmployeeService.listByEmployeePhoneAndOrgIdsPage(query, departmentList, page, 10);
//            } else {
//                list = organizationEmployeeService.listByEmployeePhonePage(query, page, 10);
//            }
//            if (CollectionUtils.isEmpty(list)) {
//                searchOrgEmpPageResponse.setEmployeeList(Collections.emptyList());
//                return new JSONResult<>(searchOrgEmpPageResponse);
//            }
//        } else if (scope.equals("4")) {
//            throw new CorpBusinessException(ExceptionCodeEnum.Alert, "待实现");
//        } else {
//            throw new CorpBusinessException(ExceptionCodeEnum.Alert, "scope字段值非法");
//        }
//        // 部门名称
//        List<String> orgIds = list.stream()
//                .filter(p -> StringUtils.isNotBlank(p.getOrgId()))
//                .map(MbOrgEmployeeInfo::getOrgId)
//                .distinct()
//                .collect(Collectors.toList());
//        // 查询部门名字
//        List<MbOrgInfo> mbOrgInfoList = organizationInfoService.listNameByOrgIds(orgIds);
//        List<SearchOrgEmpResponse> returnList = new ArrayList<>(mbOrgInfoList.size());
//        // 转成map，之后组装返回数据
//        Map<String, String> orgNameMap = mbOrgInfoList.stream()
//                .filter(p -> StringUtils.isNotBlank(p.getName()))
//                .collect(Collectors.toMap(MbOrgInfo::getOrgId, MbOrgInfo::getName));
//        for (MbOrgEmployeeInfo mbOrgEmployeeInfo : list) {
//            SearchOrgEmpResponse searchOrgEmpResponse = new SearchOrgEmpResponse();
//            searchOrgEmpResponse.setName(mbOrgEmployeeInfo.getName());
//            searchOrgEmpResponse.setPhone(mbOrgEmployeeInfo.getMobilePhone());
//            if (orgNameMap != null && orgNameMap.size() > 0) {
//                searchOrgEmpResponse.setDepartment(orgNameMap.get(mbOrgEmployeeInfo.getOrgId()));
//            }
//            searchOrgEmpResponse.setId(mbOrgEmployeeInfo.getUid());
//            returnList.add(searchOrgEmpResponse);
//        }
//        searchOrgEmpPageResponse.setEmployeeList(returnList);
//        PageInfo pageInfo = new PageInfo(list);
//        long amount = pageInfo.getTotal();
//        searchOrgEmpPageResponse.setAmount(amount);
//        return new JSONResult<>(searchOrgEmpPageResponse);
//    }

    /**
     * 获取当前岗位员工列表
     * 前端接口
     * 契约文档：http://mdoc.uat.qa.nt.ctripcorp.com:9526/project/11/interface/api/836
     * url：http://localhost:7890/employee/getEmpInPosition
     *
     * @param request
     * @return 员工列表
     */
    @RequestMapping("/getEmpInPosition")
    @ResponseBody
    public JSONResult<List<GetEmpInPositionResponse>> getEmpInPosition(@RequestBody GetEmpInPositionRequest request, HttpServletRequest httpRequest) {
        String uid = httpRequest.getParameter("uId");
        String userName = httpRequest.getParameter("userName");
        // todo 根据uid判断用户权限，需要实现
        Long postId = request.getId();
        List<GetEmpInPositionResponse> returnList = new ArrayList<>();

        List<MbOrgEmployeeInfo> list = organizationEmployeeService.listByPostId(postId);
        if (CollectionUtils.isEmpty(list)) {
            return new JSONResult<>(returnList);
        }
        // 先拿到部门名称
        List<String> orgIds = list.stream()
                .filter(p -> StringUtils.isNotBlank(p.getOrgId()))
                .map(MbOrgEmployeeInfo::getOrgId)
                .distinct()
                .collect(Collectors.toList());
        List<MbOrgInfo> mbOrgInfoList = organizationInfoService.listNameByOrgIds(orgIds);
        // 转成map，之后组装返回数据
        Map<String, String> orgNameMap = mbOrgInfoList.stream()
                .filter(p -> StringUtils.isNotBlank(p.getName()))
                .collect(Collectors.toMap(MbOrgInfo::getOrgId, MbOrgInfo::getName));
        for (MbOrgEmployeeInfo mbOrgEmployeeInfo : list) {
            GetEmpInPositionResponse getEmpInPositionResponse = new GetEmpInPositionResponse();
            getEmpInPositionResponse.setId(mbOrgEmployeeInfo.getUid());
            getEmpInPositionResponse.setLabel(mbOrgEmployeeInfo.getName());
            if (orgNameMap != null && orgNameMap.size() > 0) {
                getEmpInPositionResponse.setDepartment(orgNameMap.get(mbOrgEmployeeInfo.getOrgId()));
            }
            getEmpInPositionResponse.setStatus("1");
            returnList.add(getEmpInPositionResponse);
        }
        return new JSONResult<>(returnList);
    }

    /**
     * 提交选择员工
     * 前端接口
     * 契约文档：http://mdoc.uat.qa.nt.ctripcorp.com:9526/project/11/interface/api/836
     * url：http://localhost:7890/employee/submitSelectEmp
     *
     * @param request
     * @return 员工列表
     */
    @OperateLog(ChooseBusinesstype.CONFIGPOSITION)
    @RequestMapping("/submitSelectEmp")
    @ResponseBody
    public JSONResult submitSelectEmp(@RequestBody SubmitSelectEmpRequest request) {
        // 查询部门下所有人
        String id = request.getId();
        String type = request.getType();
        // # 1.部门
        if (type.equals(OrganizationConst.DEPARTMENT)) {
            List<SubmitSelectEmpVo> employeeList = request.getData();
            List<SubmitSelectEmpVo> needAdd = employeeList.stream()
                    .filter(p -> p.getIsNew() != null)
                    .filter(SubmitSelectEmpVo::getIsNew)
                    .distinct()
                    .collect(Collectors.toList());
            if (CollectionUtils.isEmpty(needAdd)) {
                return JSONResult.ok();
            }
            // 需要新增的人
            for (SubmitSelectEmpVo submitSelectEmpVo : needAdd) {
                MbOrgEmployeeInfo mbOrgEmployeeInfo = new MbOrgEmployeeInfo();
                mbOrgEmployeeInfo.setUid(submitSelectEmpVo.getId());
                mbOrgEmployeeInfo.setOrgId(id);
                organizationEmployeeService.update(mbOrgEmployeeInfo);
            }
            // 清除需要新增的人的负责人属性
            List<String> uids = needAdd.stream().map(SubmitSelectEmpVo::getId).distinct().collect(Collectors.toList());
            // 更新用户新鲜度表数据
            freshPassengerService.batchUpdateEmployeeOrg(uids, id);
        } else if (type.equals(OrganizationConst.POSITION)) {
            // # 2.岗位
            List<SubmitSelectEmpVo> employeeList = request.getData();
            List<SubmitSelectEmpVo> needadd = employeeList.stream()
                    .filter(p -> p.getIsNew() != null && p.getIsNew())
                    .distinct()
                    .collect(Collectors.toList());
            List<SubmitSelectEmpVo> needDel = employeeList.stream()
                    .filter(p -> p.getIsNew() != null && !p.getIsNew())
                    .distinct()
                    .collect(Collectors.toList());
            // 需要删除的人
            if (CollectionUtils.isNotEmpty(needDel)) {
                boolean b = organizationEmployeeService.clearEmployeesPosition(needDel);
            }
            // 需要新增的人
            if (CollectionUtils.isNotEmpty(needadd)) {
                boolean b = organizationEmployeeService.addEmployeesPosition(needadd, Long.valueOf(id));
//                List<String> ids = needadd.stream().map(SubmitSelectEmpVo::getId).collect(Collectors.toList());
            }
//            for (SubmitSelectEmpVo submitSelectEmpVo : needadd) {
//                MbOrgEmployeeInfo mbOrgEmployeeInfo = new MbOrgEmployeeInfo();
//                mbOrgEmployeeInfo.setUid(submitSelectEmpVo.getId());
//                mbOrgEmployeeInfo.setPostId(Long.valueOf(id));
//                organizationEmployeeService.update(mbOrgEmployeeInfo);
//            }
        }
        return JSONResult.ok();

    }

    /**
     * 模糊搜索部门下人
     * 前端接口
     * 契约文档：http://mdoc.uat.qa.nt.ctripcorp.com:9526/project/11/interface/api/836
     * url：http://localhost:7890/employee/getLeader
     *
     * @param request
     * @return 员工列表
     */
    @RequestMapping("/getLeader")
    @ResponseBody
    public JSONResult getLeader(@RequestBody GetLeaderRequest request, HttpServletRequest httpRequest) {
        String uid = httpRequest.getParameter("uId");
        String userName = httpRequest.getParameter("userName");

        String id = request.getId();
        String query = request.getQuery();
        List<MbOrgEmployeeInfo> list = organizationEmployeeService.listByNameAndOrgId(query, id);
        if (CollectionUtils.isEmpty(list)) {
            return new JSONResult<>(Collections.emptyList());
        }
        List<MbOrgEmployeeInfo> collect = list.stream().filter(p -> p.getIsLeader()).collect(Collectors.toList());
        List<GetLeaderResponse> returnList = new ArrayList<>();
        for (MbOrgEmployeeInfo mbOrgEmployeeInfo : collect) {
            GetLeaderResponse getLeaderResponse = new GetLeaderResponse();
            getLeaderResponse.setId(mbOrgEmployeeInfo.getUid());
            getLeaderResponse.setName(mbOrgEmployeeInfo.getName());
            returnList.add(getLeaderResponse);
        }
        return new JSONResult(returnList);
    }

    /**
     * 清除员工岗位信息
     * 前端接口
     *
     * @return
     */
    @RequestMapping("/clearEmployeePosition")
    public JSONResult<Boolean> clearEmployeePosition(@RequestBody SubmitSelectEmpVo submitSelectEmpVo) {
        boolean flag = organizationEmployeeService.clearEmployeesPosition(new ArrayList<SubmitSelectEmpVo>() {{
            add(submitSelectEmpVo);
        }});
        return new JSONResult<>(flag);
    }


////////////////////////////////////////////////////////////////////////////

//    /**
//     * 根据orgid和name和前后台标识查询数据
//     * url:localhost:7878/employee/listCompanyUserByOrgIdAndName
//     *
//     * @return JSONResult
//     */
//    @RequestMapping("/listCompanyUserByOrgIdAndName")
//    public JSONResult<ListUserByOrgIdAndNameResponse> listCompanyUserByOrgIdAndName(@RequestBody ListUserByOrgIdAndNameRequest request) {
//        ListUserByOrgIdAndNameResponse listUserByOrgIdAndNameResponse = new ListUserByOrgIdAndNameResponse();
//        String orgId = request.getOrgId();
//        String name = request.getName();
//        Boolean isBackgroud = request.getIsBackgroud();
//        List<OrgEmployeeVo> returnList = new ArrayList<>();
//        List<MbOrgEmployeeInfo> employeeInfoList = new ArrayList<>();
//        // 前台
//        if (!isBackgroud) {
//            if (StringUtils.isBlank(orgId)) {
//                return JSONResult.errorMsg("orgId参数缺失");
//            }
//            // 通过orgId找到org下所有orgId
//            List<String> allChildOrgIds = organizationInfoService.listRecentCompanyDirectDepartmentByOrgId(orgId);
//            if (CollectionUtils.isEmpty(allChildOrgIds)) {
//                return JSONResult.errorMsg("组织架构为空");
//            }
//            allChildOrgIds.add(orgId);
//            // 通过组织结构id查询出员工信息列表
//            employeeInfoList = organizationEmployeeService.listPageByOrgIdsAndName(allChildOrgIds, name, 1, 20);
//        } else {
//            // 查询后台用户
//            employeeInfoList = organizationEmployeeService.listBackUserByName(name, 1, 20);
//        }
//        // 数据为空
//        if (CollectionUtils.isEmpty(employeeInfoList)) {
//            listUserByOrgIdAndNameResponse.setApproveUsers(Collections.emptyList());
//            return JSONResult.success(listUserByOrgIdAndNameResponse);
//        }
//        // 筛选出所有组织架构id
//        List<String> orgIds = employeeInfoList.stream().map(MbOrgEmployeeInfo::getOrgId).distinct().collect(Collectors.toList());
//        // 查询出组织结构名称
//        List<MbOrgInfo> orgInfoList = organizationInfoService.listNameByOrgIds(orgIds);
//        Map<String, List<MbOrgInfo>> orgMap = orgInfoList.stream().collect(Collectors.groupingBy(mbOrgInfo -> mbOrgInfo.getOrgId()));
//        for (MbOrgEmployeeInfo mbOrgEmployeeInfo : employeeInfoList) {
//            OrgEmployeeVo orgEmployeeVo = new OrgEmployeeVo();
//            orgEmployeeVo.setUid(mbOrgEmployeeInfo.getUid());
//            orgEmployeeVo.setName(mbOrgEmployeeInfo.getName());
//            List<MbOrgInfo> mbOrgInfoList = orgMap.get(mbOrgEmployeeInfo.getOrgId());
//            if (CollectionUtils.isNotEmpty(mbOrgInfoList)) {
//                orgEmployeeVo.setOrgName(mbOrgInfoList.get(0).getName());
//            }
//            orgEmployeeVo.setOrgId(mbOrgEmployeeInfo.getOrgId());
//            orgEmployeeVo.setValid(mbOrgEmployeeInfo.getValid());
//            returnList.add(orgEmployeeVo);
//        }
//        listUserByOrgIdAndNameResponse.setApproveUsers(returnList);
//        return JSONResult.success(listUserByOrgIdAndNameResponse);
//    }

    /**
     * 通过key模糊匹配用户名和手机号
     *
     * @param employeeSubscriptionRequest
     * @return
     */
    @RequestMapping("/fuzzyByNameAndTel")
    public JSONResult<EmployeeSubscriptionResponse> fuzzyByNameAndTel(@RequestBody EmployeeSubscriptionRequest employeeSubscriptionRequest) {
        EmployeeSubscriptionResponse employeeSubscriptionResponse = new EmployeeSubscriptionResponse();
        // 查询数据库数据
        List<MbOrgEmployeeInfo> list = organizationEmployeeService.fuzzyByNameAndTel(employeeSubscriptionRequest.getKey(),
                employeeSubscriptionRequest.getPageNum(),
                employeeSubscriptionRequest.getPageSize(),
                employeeSubscriptionRequest.getOrgValid());
        if (CollectionUtils.isEmpty(list)) {
            employeeSubscriptionResponse.setCount(0L);
            employeeSubscriptionResponse.setCurrentPage(employeeSubscriptionRequest.getPageNum());
            employeeSubscriptionResponse.setList(Collections.emptyList());
            employeeSubscriptionResponse.setPageSize(employeeSubscriptionRequest.getPageSize());
            employeeSubscriptionResponse.setTotalPage(0);
            return new JSONResult<>(employeeSubscriptionResponse);
        }
        // 封装子公司名
        List<MbOrgEmployeeInfoDto> mbOrgEmployeeInfoDtos = organizationInfoService.batchFindRecentCompanyIdByOrgId(list);
        List<EmployeeSubscriptionResponse.EmployeeSubscriptionVo> employeeSubscriptionVoList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(mbOrgEmployeeInfoDtos)) {
            for (MbOrgEmployeeInfoDto mbOrgEmployeeInfoDto : mbOrgEmployeeInfoDtos) {
                EmployeeSubscriptionResponse.EmployeeSubscriptionVo employeeSubscriptionVo = new EmployeeSubscriptionResponse.EmployeeSubscriptionVo();
                BeanUtils.copyProperties(mbOrgEmployeeInfoDto, employeeSubscriptionVo);
                employeeSubscriptionVoList.add(employeeSubscriptionVo);
            }
        }
        employeeSubscriptionResponse.setList(employeeSubscriptionVoList);
        PageInfo<MbOrgEmployeeInfo> pageInfo = new PageInfo<>(list);
        employeeSubscriptionResponse.setCount(pageInfo.getTotal());
        employeeSubscriptionResponse.setCurrentPage(employeeSubscriptionRequest.getPageNum());
        employeeSubscriptionResponse.setPageSize(employeeSubscriptionRequest.getPageSize());
        employeeSubscriptionResponse.setTotalPage(pageInfo.getPages());
        return new JSONResult<>(employeeSubscriptionResponse);
    }

    /**
     * 是不是后台用户
     *
     * @param uid
     * @return
     */
    @RequestMapping("/isBackgrounUser")
    public JSONResult<Boolean> isBackgrounUser(String uid) {
        if (StringUtils.isBlank(uid)) {
            return new JSONResult<>(false);
        }
        MbOrgEmployeeInfo mbOrgEmployeeInfo = organizationEmployeeService.findByUid(uid);
        Boolean isBackground = mbOrgEmployeeInfo.getIsBackground();
        return new JSONResult<>(isBackground);
    }

    /**
     * 查询单个用户信息
     * url:
     * http://localhost:7890/employee/findEmployeeInfoByUid?uid=_SL002
     *
     * @param uid 用户id
     * @return JSONResultgetOrg
     */
    @RequestMapping("/findEmployeeInfoByUid")
    public JSONResult<OrgEmployeeVo> findEmployeeInfoByUid(@RequestParam(name = "uid") String uid, @RequestParam(name = "orgId") String orgId) {
        return JSONResult.success(organizationEmployeeService.searchEmployeeInfo(SearchEmployeeInfoRequestBO.create(uid, orgId)));
    }

    @RequestMapping("/findEmployeeInfo")
    public JSONResult<OrgEmployeeVo> findEmployeeInfo(@RequestBody SearchEmployeeInfoRequestBO request) {
        return JSONResult.success(organizationEmployeeService.searchEmployeeInfo(request));
    }

    @RequestMapping(value = "/findOrgInfoByUid")
    public JSONResult<List<OrgEmployeeVo>> findOrgInfoByUid(@RequestParam(name = "uid") String uid) {
        return JSONResult.success(organizationEmployeeService.findOrgInfoByUid(uid));
    }

    /**
     * 批量获取员工信息
     *
     * @return
     */
    @RequestMapping("/listEmployeeInfoByIds")
    public JSONResult<List<OrgEmployeeVo>> listEmployeeInfoByIds(@RequestParam(name = "ids") List<String> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return new JSONResult<>(Collections.emptyList());
        }
        List<MbOrgEmployeeInfo> list = organizationEmployeeService.listByUids(ids);
        List<OrgEmployeeVo> returnList = new ArrayList<>();
        for (MbOrgEmployeeInfo mbOrgEmployeeInfo : list) {
            OrgEmployeeVo orgEmployeeVo = new OrgEmployeeVo();
            BeanUtils.copyProperties(mbOrgEmployeeInfo, orgEmployeeVo);
            returnList.add(orgEmployeeVo);
        }
        return new JSONResult<>(returnList);

    }

    /**
     * 批量获取员工信息
     *
     * @return
     */
    @RequestMapping("/queryUserOrgRelation")
    public JSONResult<List<MbUserOrgRelationVo>> queryUserOrgRelation(@RequestBody List<MbUserOrgRelationVo> queryVoList) {
        if (CollectionUtils.isEmpty(queryVoList)) {
            return new JSONResult<>(Collections.emptyList());
        }
        List<MbUserOrgRelationVo> result = new ArrayList<>();
        for (MbUserOrgRelationVo queryVo : queryVoList) {
            MbUserOrgRelation query = new MbUserOrgRelation();
            BeanUtils.copyProperties(queryVo, query);
            MbUserOrgRelation mbUserOrgRelation = userOrgRelationService.get(query);
            MbUserOrgRelationVo mbUserOrgRelationVo = new MbUserOrgRelationVo();
            BeanUtils.copyProperties(mbUserOrgRelation, mbUserOrgRelationVo);
            result.add(mbUserOrgRelationVo);
        }
        return new JSONResult<>(result);

    }

//    /**
//     * 通过组织结构id找到部门下所有员工信息，分页(分页，排序按照 leader，sleader，vip排序，之后按照创建时间正序)，再分别查出部门负责人，次级负责人，员工总数
//     * 后端接口
//     * 本地访问地址：http://localhost:7890/employee/listEmployeeByOrgId?orgId=1&name=&pageNum=&pageSize=
//     *
//     * @param orgId    组织结构id,分页参数
//     * @param name     用户姓名
//     * @param pageNum  当前页数
//     * @param pageSize 每页显示条数
//     * @return JSONResult
//     */
//    @RequestMapping("/listEmployeeByOrgId")
//    @ResponseBody
//    public JSONResult<Page> listEmployeeByOrgId(String orgId, String name, Integer pageNum, Integer pageSize) {
//        if (StringUtils.isBlank(orgId)) {
//            return JSONResult.errorMsg("orgId参数缺失");
//        }
//        // 通过orgId找到org下所有orgId
//        List<String> allChildOrgIds = new ArrayList<>();
//        organizationInfoService.findAllChildOrgIdsByOrgId(orgId, allChildOrgIds);
//        if (CollectionUtils.isEmpty(allChildOrgIds)) {
//            return JSONResult.errorMsg("error");
//        }
//        allChildOrgIds.add(orgId);
//        // 通过组织结构id查询出员工信息列表
//        List<MbOrgEmployeeInfo> employeeInfoList = organizationEmployeeService.listPageByOrgIdsAndName(allChildOrgIds, name, pageNum, pageSize);
//        if (CollectionUtils.isEmpty(employeeInfoList)) {
//            return JSONResult.errorMsg("error");
//        }
//        // 筛选出所有组织架构id
//        List<String> orgIds = employeeInfoList.stream().map(MbOrgEmployeeInfo::getOrgId).distinct().collect(Collectors.toList());
//        // 查询出组织结构名称
//        List<MbOrgInfo> orgInfoList = organizationInfoService.listNameByOrgIds(orgIds);
//        Map<String, List<MbOrgInfo>> orgMap = orgInfoList.stream().collect(Collectors.groupingBy(mbOrgInfo -> mbOrgInfo.getOrgId()));
//
//        List<OrgEmployeeVo> returnList = new ArrayList<>();
//        for (MbOrgEmployeeInfo mbOrgEmployeeInfo : employeeInfoList) {
//            OrgEmployeeVo orgEmployeeVo = new OrgEmployeeVo();
//            orgEmployeeVo.setUid(mbOrgEmployeeInfo.getUid());
//            orgEmployeeVo.setName(mbOrgEmployeeInfo.getName());
//            List<MbOrgInfo> mbOrgInfoList = orgMap.get(mbOrgEmployeeInfo.getOrgId());
//            if (CollectionUtils.isNotEmpty(mbOrgInfoList)) {
//                orgEmployeeVo.setOrgName(mbOrgInfoList.get(0).getName());
//            }
//            orgEmployeeVo.setOrgId(mbOrgEmployeeInfo.getOrgId());
//            returnList.add(orgEmployeeVo);
//        }
//        PageInfo page = new PageInfo<>(employeeInfoList);
//        page.getTotal();
//        return JSONResult.success(new Page(page.getPageNum(), page.getPageSize(), page.getLastPage(), page.getTotal(), returnList));
//    }

    /**
     * 根据部门id获得部门负责人信息
     * url:
     * http://localhost:7890/employee/findLeaderByOrgId?orgId=7
     *
     * @param orgId 部门id
     * @return 负责人uid，姓名
     */
    @RequestMapping("/findLeaderByOrgId")
    public JSONResult<List<OrgEmployeeVo>> findLeaderByOrgId(@RequestParam(name = "orgId") String orgId) {
        List<OrgEmployeeVo> returnList = CollUtil.newArrayList();
        // 查询部门负责人信息
        List<MbUserOrgRelation> result = userOrgRelationService.listLeader(orgId);
        if (CollUtil.isEmpty(result)) {
            return new JSONResult<>(returnList);
        }
        List<String> uids = result.stream().map(MbUserOrgRelation::getUid).collect(Collectors.toList());
        List<MbOrgEmployeeInfo> list = organizationEmployeeService.listByUids(uids);
        if (CollUtil.isEmpty(list)) {
            return new JSONResult<>(returnList);
        }
        Map<String, MbOrgEmployeeInfo> userMap = list.stream().collect(Collectors.toMap(MbOrgEmployeeInfo::getUid, p -> p));
        for (MbUserOrgRelation mbUserOrgRelation : result) {
            OrgEmployeeVo orgEmployeeVo = new OrgEmployeeVo();
            orgEmployeeVo.setUid(mbUserOrgRelation.getUid());
            orgEmployeeVo.setOrgId(mbUserOrgRelation.getOrgId());
            orgEmployeeVo.setName(userMap.get(mbUserOrgRelation.getUid()).getName());
            orgEmployeeVo.setValid(userMap.get(mbUserOrgRelation.getUid()).getValid());
            returnList.add(orgEmployeeVo);
        }
        return new JSONResult<>(returnList);
    }

    /**
     * 查询所有负责人
     * @return
     */
    @RequestMapping("/findAllLeaders")
    public JSONResult<List<OrgEmployeeVo>> findAllLeaders() {
        List<OrgEmployeeVo> returnList = CollUtil.newArrayList();
        // 查询部门负责人信息
        List<MbUserOrgRelation> result = userOrgRelationService.listAllLeaders();
        if (CollUtil.isEmpty(result)) {
            return new JSONResult<>(returnList);
        }
        List<String> uids = result.stream().map(MbUserOrgRelation::getUid).collect(Collectors.toList());
        List<MbOrgEmployeeInfo> list = organizationEmployeeService.listByUids(uids);
        if (CollUtil.isEmpty(list)) {
            return new JSONResult<>(returnList);
        }
        Map<String, MbOrgEmployeeInfo> userMap = list.stream().collect(Collectors.toMap(MbOrgEmployeeInfo::getUid, p -> p));
        for (MbUserOrgRelation mbUserOrgRelation : result) {
            OrgEmployeeVo orgEmployeeVo = new OrgEmployeeVo();
            orgEmployeeVo.setUid(mbUserOrgRelation.getUid());
            orgEmployeeVo.setOrgId(mbUserOrgRelation.getOrgId());
            orgEmployeeVo.setName(userMap.get(mbUserOrgRelation.getUid()).getName());
            orgEmployeeVo.setValid(userMap.get(mbUserOrgRelation.getUid()).getValid());
            returnList.add(orgEmployeeVo);
        }
        return new JSONResult<>(returnList);
    }

    /**
     * 通过uid查询用户的部门id
     * http://localhost:7890/employee/findDepartmentIdByUid?uid=_SL00000
     *
     * @param uid 用户id
     * @return 部门id
     */
    @RequestMapping("/findDepartmentIdByUid")
    public String findDepartmentIdByUid(String uid) {
        MbOrgEmployeeInfo mbOrgEmployeeInfo = organizationEmployeeService.findByUid(uid);
        return mbOrgEmployeeInfo == null ? null : mbOrgEmployeeInfo.getOrgId();
    }

    /**
     * 通过uid查询用户的部门id
     * http://localhost:7890/employee/findDepartmentInfoByUid?uid=_SL00000
     *
     * @param uid 用户id
     * @return 部门id
     */
    @RequestMapping("/findDepartmentInfoByUid")
    public JSONResult<OrgInfoVo> findDepartmentInfoByUid(String uid) {
        MbOrgEmployeeInfo mbOrgEmployeeInfo = organizationEmployeeService.findByUid(uid);
        if (mbOrgEmployeeInfo == null) {
            return new JSONResult<>(null);
        }
        String orgId = mbOrgEmployeeInfo.getOrgId();
        if (StringUtils.isBlank(orgId)) {
            return new JSONResult<>(null);
        }
        MbOrgInfo mb = organizationInfoService.findByOrgId(orgId);
        if (mb == null) {
            return new JSONResult<>(null);
        }
        OrgInfoVo orgInfoVo = new OrgInfoVo();
        BeanUtils.copyProperties(mb, orgInfoVo);
        return new JSONResult<>(orgInfoVo);
    }

    /**
     * 通过组织结构id找到部门下所有员工信息，无需分页，无需查找当前部门信息，用户分配岗位时候拉去所有人
     * http://localhost:7890/employee/listAllEmployeeByDepartmentId?org=1
     *
     * @param orgId 组织结构id
     * @return JSONResult 员工列表，uid，name，postId
     */
    @RequestMapping("/listAllEmployeeByDepartmentId")
    @ResponseBody
    public JSONResult<List<OrgEmployeeVo>> listAllEmployeeByDepartmentId(@RequestParam(name = "orgId") String orgId) {
        if (orgId == null) {
            return JSONResult.errorMsg("orgId缺失");
        }
        List<OrgEmployeeVo> returnList = new ArrayList<>();
        List<MbOrgEmployeeInfo> list = organizationEmployeeService.listAllByDepartmentIdAndName(orgId, null);
        if (CollectionUtils.isNotEmpty(list)) {
            // 组装数据返回
            for (MbOrgEmployeeInfo mbOrgEmployeeInfo : list) {
                OrgEmployeeVo orgEmployeeVo = new OrgEmployeeVo();
                orgEmployeeVo.setUid(mbOrgEmployeeInfo.getUid());
                orgEmployeeVo.setName(mbOrgEmployeeInfo.getName());
                orgEmployeeVo.setPostId(mbOrgEmployeeInfo.getPostId());
                orgEmployeeVo.setOrgId(mbOrgEmployeeInfo.getOrgId());
                returnList.add(orgEmployeeVo);
            }
        }
        return new JSONResult<>(returnList);
    }

//    /**
//     * 模糊搜索员工
//     *
//     * @param request
//     * @return
//     */
//    @RequestMapping("/fuzzySearch")
//    public JSONResult searchEmployeeInfoList(@RequestBody SearchEmployeeInfoRequest request) {
//        List<SearchEmployeeInfo> list = organizationEmployeeService.searchEmployeeInfoList(request);
//        return JSONResult.success(list);
//    }

//    /**
//     * 查询末级子公司下的所有部门的人，部门包括子部门
//     * 后端接口
//     * 本地访问地址：http://localhost:7890/employee/listAllDepartmentEmployeeByCompanyId?orgId=1&name=&pageNum=&pageSize=
//     *
//     * @param orgId    组织结构id,分页参数
//     * @param name     用户姓名
//     * @param pageNum  当前页数
//     * @param pageSize 每页显示条数
//     * @return JSONResult
//     */
//    @RequestMapping("/listAllDepartmentEmployeeByCompanyId")
//    @ResponseBody
//    public JSONResult<Page> listAllDepartmentEmployeeByCompanyId(String orgId, String name, Integer pageNum, Integer pageSize) {
//        if (StringUtils.isBlank(orgId)) {
//            return JSONResult.errorMsg("orgId参数缺失");
//        }
//        // 通过orgId找到org下所有orgId
//        List<String> allChildOrgIds = organizationInfoService.listRecentCompanyDirectDepartmentByOrgId(orgId);
//        if (CollectionUtils.isEmpty(allChildOrgIds)) {
//            return JSONResult.errorMsg("error");
//        }
//        allChildOrgIds.add(orgId);
//        // 通过组织结构id查询出员工信息列表
//        List<MbOrgEmployeeInfo> employeeInfoList = organizationEmployeeService.listPageByOrgIdsAndName(allChildOrgIds, name, pageNum, pageSize);
//        if (CollectionUtils.isEmpty(employeeInfoList)) {
//            return JSONResult.errorMsg("error");
//        }
//        // 筛选出所有组织架构id
//        List<String> orgIds = employeeInfoList.stream().map(MbOrgEmployeeInfo::getOrgId).distinct().collect(Collectors.toList());
//        // 查询出组织结构名称
//        List<MbOrgInfo> orgInfoList = organizationInfoService.listNameByOrgIds(orgIds);
//        Map<String, List<MbOrgInfo>> orgMap = orgInfoList.stream().collect(Collectors.groupingBy(mbOrgInfo -> mbOrgInfo.getOrgId()));
//
//        List<OrgEmployeeVo> returnList = new ArrayList<>();
//        for (MbOrgEmployeeInfo mbOrgEmployeeInfo : employeeInfoList) {
//            OrgEmployeeVo orgEmployeeVo = new OrgEmployeeVo();
//            orgEmployeeVo.setUid(mbOrgEmployeeInfo.getUid());
//            orgEmployeeVo.setName(mbOrgEmployeeInfo.getName());
//            List<MbOrgInfo> mbOrgInfoList = orgMap.get(mbOrgEmployeeInfo.getOrgId());
//            if (CollectionUtils.isNotEmpty(mbOrgInfoList)) {
//                orgEmployeeVo.setOrgName(mbOrgInfoList.get(0).getName());
//            }
//            orgEmployeeVo.setOrgId(mbOrgEmployeeInfo.getOrgId());
//            orgEmployeeVo.setValid(mbOrgEmployeeInfo.getValid());
//            returnList.add(orgEmployeeVo);
//        }
//        PageInfo page = new PageInfo<>(employeeInfoList);
//        page.getTotal();
//        return JSONResult.success(new Page(page.getPageNum(), page.getPageSize(), page.getLastPage(), page.getTotal(), returnList));
//    }

    /**
     * 查询用户id查询用户所在末级子公司和部门信息
     *
     * @param uid 用户id
     * @return 末级公司id，人名，直属部门id
     */
    @RequestMapping(value = "/findRecentCompanyAndMyDepartmentInfoByUid")
    public JSONResult<OrgEmployeeVo> findRecentCompanyAndMyDepartmentInfoByUid(@RequestParam(value = "uid") String uid) {
        MbOrgEmployeeInfo mbOrgEmployeeInfo = organizationEmployeeService.findByUid(uid);
        if (mbOrgEmployeeInfo == null) {
            return JSONResult.errorMsg("用户信息为空");
        }
        if (mbOrgEmployeeInfo.getIsBackground()) {
            return JSONResult.errorMsg("后台用户无法查询前端组织架构接口");
        }
        String orgId = mbOrgEmployeeInfo.getOrgId();
        if (StringUtils.isBlank(orgId)) {
            return JSONResult.errorMsg("用户部门信息为空");
        }
        MbOrgInfo mbOrgInfo = organizationInfoService.findRecentCompanyIdByOrgId(orgId);
        OrgEmployeeVo orgEmployeeVo = new OrgEmployeeVo();
        BeanUtils.copyProperties(mbOrgEmployeeInfo, orgEmployeeVo);
        orgEmployeeVo.setRecentCompanyId(mbOrgInfo.getOrgId());
        orgEmployeeVo.setRecentCompanyName(mbOrgInfo.getName());
        return JSONResult.success(orgEmployeeVo);
    }

    /**
     * 查询用户角色
     *
     * @param uid 用户id
     * @return 岗位权限（0：普通员工 1：行政秘书 2：涉外秘书）
     */
    @RequestMapping(value = "/findEmployeeRightByUid")
    public JSONResult<String> findEmployeeRightByUid(@RequestParam(name = "uid") String uid) {
        MbOrgEmployeeInfo dbUserInfo = organizationEmployeeService.findByUid(uid);
        Long postId = dbUserInfo.getPostId();
        if (postId != null) {
            MbPostInfo mbPostInfo = postService.find(postId);
            if (mbPostInfo != null) {
                return new JSONResult<>(mbPostInfo.getRights());
            }
        }
        return new JSONResult<>(null);
    }

//    @PostMapping("/existence")
//    public CheckUserExistsResp checkEmpExists(@RequestBody CheckUserExistsReq reqs) {
//        List<String> uids = new ArrayList<>();
//        try {
//            if (reqs.getUserInfo() == null || reqs.getUserInfo().isEmpty()) {
//                return new CheckUserExistsResp(false, "查询的用户个数不能为空",
//                        Integer.parseInt(ErrorCodeEnum.UN_SUPPORT_REQ_METHOD.getCode()), null);
//            }
//            if (reqs.getUserInfo().size() > 20) {
//                return new CheckUserExistsResp(false, "一次最多只能查询20条",
//                        Integer.parseInt(ErrorCodeEnum.UN_SUPPORT_REQ_METHOD.getCode()), null);
//            }
//            organizationEmployeeService.checkEmpExistence(reqs, uids);
//            CheckUserExistsResp resp = new CheckUserExistsResp(true, "", null, uids);
//            resp.setUids(uids);
//            return resp;
//        } catch (CommonException e) {
//            return new CheckUserExistsResp(false, e.getErrMsg(), e.getErrCode(), uids);
//        }
//    }

    /**
     * 查询用户的登录身份信息
     *
     * @param request request
     * @return ListUserOrgRelationForLoginResponse
     */
    @RequestMapping(value = "/listUserOrgRelationForLogin")
    public JSONResult<List<ListUserOrgRelationForLoginResponse>> listUserOrgRelationForLogin(@RequestBody @Valid ListUserOrgRelationForLoginRequest request) {
        return JSONResult.success(userOrgRelationService.listUserOrgRelationForLogin(request));
    }

    /**
     * 查询用户的登录身份信息
     *
     * @param addUserInfoRequest request
     * @return uid
     */
    @RequestMapping(value = "/addUserInfo")
    @Transactional(rollbackFor = Exception.class)
    public JSONResult<String> addUserInfo(@RequestBody @Valid AddUserInfoRequest addUserInfoRequest) {
        try {
            String uid = addUserInfoRequest.getUid();
            Integer cardType = addUserInfoRequest.getCardType();
            String cardNo = addUserInfoRequest.getCardNo();
            // 保存用户信息
            if (StrUtil.isEmpty(uid)) {
                MbOrgEmployeeInfo mbOrgEmployeeInfo = new MbOrgEmployeeInfo();
                mbOrgEmployeeInfo.setName(addUserInfoRequest.getName());
                mbOrgEmployeeInfo.setEmail(addUserInfoRequest.getEmail());
                mbOrgEmployeeInfo.setValid(CommonConst.TRUE);
                mbOrgEmployeeInfo.setIsBackground(Boolean.FALSE);
                uid = UUID.randomUUID().toString();
                mbOrgEmployeeInfo.setUid(uid);
                mbOrgEmployeeInfo.setAreaCode(addUserInfoRequest.getAreaCode());
                mbOrgEmployeeInfo.setMobilePhone(addUserInfoRequest.getMobilePhone());
                mbOrgEmployeeInfo.setGender(addUserInfoRequest.getGender());
                mbOrgEmployeeInfo.setNationality("CN|中国大陆");
                MbOrgEmployeeInfo record = new MbOrgEmployeeInfo();
                record.setIsBackground(false);
                record.setMobilePhone(addUserInfoRequest.getMobilePhone());
                record.setAreaCode(addUserInfoRequest.getAreaCode());
                record.setDeleteTime(new Date(0));
                MbOrgEmployeeInfo oldEmployeeInfo = mbOrgEmployeeLoader.selectOneByRecord(record);
                log.info("addUserInforequest:{}, result:{}", JsonUtils.toJsonString(record), JsonUtils.toJsonString(oldEmployeeInfo));
                if (oldEmployeeInfo != null) {
                    throw new CorpBusinessException(OrganizationResponseCodeEnum.EMPLOYEE_PHONE_NO_EXIST);
                }
                boolean flag = organizationEmployeeService.create(mbOrgEmployeeInfo);
                if (!flag) {
                    throw new CorpBusinessException(OrganizationResponseCodeEnum.USER_CREATE_ERROR);
                }
                // 绑定兑换码
                redemptionCodeService.bindRedemptionCode(mbOrgEmployeeInfo.getUid(), mbOrgEmployeeInfo.getName());
                // 判断用户证件是否存在，如果存在就更新，否则保存证件信息
                if (cardType != null) {
                    // 检查证件是否重复，重复判断依据是 type+number唯一
                    List<MbOrgUserIdcard> cardList = organizationUserIdCardService.findByTypeAndNo(cardType, cardNo);
                    if (CollUtil.isNotEmpty(cardList)) {
                        throw new CorpBusinessException(OrganizationResponseCodeEnum.CARD_EXISTS);
                    }

                    MbOrgUserIdcard card = organizationUserIdCardService.findByEmployeeUidAndType(uid, cardType);
                    if (card == null) {
                        MbOrgUserIdcard mbOrgUserIdcard = new MbOrgUserIdcard();
                        mbOrgUserIdcard.setCardType(cardType);
                        mbOrgUserIdcard.setCardNo(cardNo);
                        mbOrgUserIdcard.setEmployeeUid(uid);
                        boolean cardFlag = organizationUserIdCardService.save(mbOrgUserIdcard);
                        if (!cardFlag) {
                            throw new CorpBusinessException(OrganizationResponseCodeEnum.SAVE_CARD_FAILED);
                        }
                        log.info("保存用户证件成功");
                    } else {
                        MbOrgUserIdcard mbOrgUserIdcard = new MbOrgUserIdcard();
                        mbOrgUserIdcard.setEmployeeUid(uid);
                        mbOrgUserIdcard.setCardType(cardType);
                        mbOrgUserIdcard.setCardNo(cardNo);
                        boolean updateFlag = organizationUserIdCardService.updateEmployeeCard(mbOrgUserIdcard);
                        log.info("更新用户证件成功");
                    }
                }
            }

            // 先判断用户关系是否存在，如果存在不做处理。保存关系表。默认审批中状态
            List<String> orgIds = addUserInfoRequest.getOrgIds();
            List<MbUserOrgRelation> needSaveList = CollUtil.newArrayList();
            for (String orgId : orgIds) {
                MbUserOrgRelation dbData = userOrgRelationService.find(orgId, uid);
                if (dbData != null) {
                    log.info("用户[{}]组织[{}]已经存在用户身份", uid, orgId);
                    continue;
                }
                MbUserOrgRelation mbUserOrgRelation = new MbUserOrgRelation();
                mbUserOrgRelation.setOrgId(orgId);
                mbUserOrgRelation.setUid(uid);
                mbUserOrgRelation.setStatus(UserOrgRelationStatusEnum.VERIFY.getStatus());
                needSaveList.add(mbUserOrgRelation);
            }
            if (CollUtil.isNotEmpty(needSaveList)) {
                // 批量保存用户身份信息
                boolean relationFlag = userOrgRelationService.batchSave(needSaveList);
                if (!relationFlag) {
                    throw new CorpBusinessException(OrganizationResponseCodeEnum.USER_CREATE_ERROR);
                }
                // 新增用户到新鲜度出行人表
                List<MbFreshPassenger> freshList = new ArrayList<>();
                for (MbUserOrgRelation mbUserOrgRelation : needSaveList) {
                    MbFreshPassenger mbFreshPassenger = new MbFreshPassenger();
                    mbFreshPassenger.setEmployeeUid(uid);
                    mbFreshPassenger.setOrgId(mbUserOrgRelation.getOrgId());
                    mbFreshPassenger.setName(addUserInfoRequest.getName());
                    mbFreshPassenger.setFreshTime(new Date());
                    mbFreshPassenger.setValid(Boolean.TRUE);
                    freshList.add(mbFreshPassenger);
                }
                freshPassengerService.batchSave(freshList);

                //新增常旅
                MbFreshPassengerRelation mbFreshPassengerRelation = new MbFreshPassengerRelation();
                mbFreshPassengerRelation.setEmployeeFlag(1);
                mbFreshPassengerRelation.setFreshUid(uid);
                mbFreshPassengerRelation.setFreshTime(new Date());
                mbFreshPassengerRelation.setIsDeleted(false);
                mbFreshPassengerRelation.setUid(uid);
                mbFreshPassengerRelation.setDatachangeLasttime(new Date());
                mbFreshPassengerRelation.setDatachangeCreatetime(new Date());
                freshPassengerRelationService.save(mbFreshPassengerRelation);
            }

            return new JSONResult<>(uid);
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return JSONResult.errorMsg(500, e.getMessage());
        }

    }

    /**
     * 岗位—人员信息列表_新增员工初始化
     *
     * @param addUserInfoFrontInitRequest
     * @return
     */
    @RequestMapping("/addUserInfoFrontInit")
    public JSONResult<AddUserInfoFrontInitResponse> addUserInfoFrontInit(@RequestBody @Valid AddUserInfoFrontInitRequest addUserInfoFrontInitRequest) {
        AddUserInfoFrontInitResponse addUserInfoFrontInitResponse = new AddUserInfoFrontInitResponse();
        String phoneNum = addUserInfoFrontInitRequest.getPhoneNum();
        String orgId = addUserInfoFrontInitRequest.getOrgId();
        String areaCode = addUserInfoFrontInitRequest.getAreaCode();
        UserLoginRequest request = new UserLoginRequest();
        request.setPhoneNum(phoneNum);
        request.setCountryCode(areaCode);
        // 根据手机号查询用户账号
        MbUserLogin userLogin = userLoginService.getByPhoneNumAndCountryCodeAndBgUser(request.getPhoneNum(), request.getCountryCode(), false);
        // 账号是否存在
        boolean ifExist = Boolean.FALSE;
        // 账号是否禁用
        boolean enabled = Boolean.TRUE;
        String uid = null;
        if (userLogin != null) {
            if (StrUtil.isNotEmpty(userLogin.getUid())) {
                ifExist = true;
                enabled = userLogin.getStatus() == 1;
                uid = userLogin.getUid();
            }
        }
        // 账号被停用，不允许添加。
        if (!enabled) {
            addUserInfoFrontInitResponse.setIsAbled(Boolean.TRUE);
            return new JSONResult<>(addUserInfoFrontInitResponse);
        }
        addUserInfoFrontInitResponse.setIsAbled(Boolean.FALSE);
        if (ifExist) {
            // 判断组织下是否存在
            MbUserOrgRelation mbUserOrgRelation = userOrgRelationService.find(orgId, uid);
            if (mbUserOrgRelation != null) {
                addUserInfoFrontInitResponse.setIsExist(true);
                return new JSONResult<>(addUserInfoFrontInitResponse);
            }
            addUserInfoFrontInitResponse.setIsExist(false);
        } else {
            addUserInfoFrontInitResponse.setIsExist(false);
            return new JSONResult<>(addUserInfoFrontInitResponse);
        }
        // 当前组织下不存在，返回用户信息
        // 查询用户信息
        MbOrgEmployeeInfo employeeInfo = organizationEmployeeService.findByUid(uid);
        OrgEmployeeVo orgEmployeeVo = new OrgEmployeeVo();
        orgEmployeeVo.setName(employeeInfo.getName());
        orgEmployeeVo.setEmail(employeeInfo.getEmail());
        orgEmployeeVo.setUid(employeeInfo.getUid());
        String gender = employeeInfo.getGender();
        if (StrUtil.isNotBlank(gender)) {
            orgEmployeeVo.setGender(gender.equals(OrgEmployeeConst.MAN) ? "0" : "1");
        }
        addUserInfoFrontInitResponse.setUserInfo(orgEmployeeVo);
        return new JSONResult<>(addUserInfoFrontInitResponse);
    }

    /**
     * 组织架构/岗位—人员信息列表_新增员工
     *
     * @param addUserInfoFrontRequest request
     * @return uid
     */
    @RequestMapping(value = "/addUserInfoFront")
    @Transactional(rollbackFor = Exception.class)
    public JSONResult<Boolean> addUserInfoFront(@RequestBody @Valid AddUserInfoFrontRequest addUserInfoFrontRequest) {
        // 根据手机号查询用户账号
        String phoneNum = addUserInfoFrontRequest.getPhoneNum();
        String orgId = addUserInfoFrontRequest.getOrgId();
        String uid = addUserInfoFrontRequest.getUid();
        String areaCode = addUserInfoFrontRequest.getAreaCode();
        UserLoginRequest request = new UserLoginRequest();
        request.setPhoneNum(phoneNum);
        request.setCountryCode(areaCode);
        MbUserLogin userLogin = userLoginService.getByPhoneNumAndCountryCodeAndBgUser(request.getPhoneNum(), request.getCountryCode(), false);
        // 账号是否存在
        boolean ifExist = Boolean.FALSE;
        // 账号是否禁用
        boolean enabled = Boolean.TRUE;
        if (userLogin != null) {
            ifExist = true;
            enabled = userLogin.getStatus() == 1;
        }
        // 账号被停用，不允许添加。
        if (!enabled) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.ACCOUNT_ENABLED);
        }
        // 对身份做重复校验
        if (StrUtil.isNotEmpty(uid)) {
            MbUserOrgRelation mbUserOrgRelation = userOrgRelationService.find(orgId, uid);
            if (mbUserOrgRelation != null && !mbUserOrgRelation.getStatus().equals(UserOrgRelationStatusEnum.REFUSE)) {
                throw new CorpBusinessException(OrganizationResponseCodeEnum.USER_ALREADY_EXISTS);
            }
            // 添加一个身份
            MbUserOrgRelation data = new MbUserOrgRelation();
            data.setUid(uid);
            data.setOrgId(orgId);
            data.setStatus(UserOrgRelationStatusEnum.NORMAL.getStatus());
            userOrgRelationService.save(data);
            log.info("添加用户身份成功uid:[{}],orgId[{}]", uid, orgId);
            // 新增用户到新鲜度出行人表
            MbFreshPassenger mbFreshPassenger = new MbFreshPassenger();
            mbFreshPassenger.setEmployeeUid(uid);
            mbFreshPassenger.setOrgId(addUserInfoFrontRequest.getOrgId());
            mbFreshPassenger.setName(addUserInfoFrontRequest.getName());
            mbFreshPassenger.setFreshTime(new Date());
            mbFreshPassenger.setValid(Boolean.FALSE);
            freshPassengerService.save(mbFreshPassenger);
            return new JSONResult<>(Boolean.TRUE);
        }

        // 检查证件是否重复，重复判断依据是 type+number唯一
        String cardType = addUserInfoFrontRequest.getCardType();
        String cardNo = addUserInfoFrontRequest.getCardNo();
        List<MbOrgUserIdcard> cardList = organizationUserIdCardService.findByTypeAndNo(Integer.valueOf(cardType), cardNo);
        if (CollUtil.isNotEmpty(cardList)) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.CARD_EXISTS);
        }

        // 保存用户信息
        MbOrgEmployeeInfo mbOrgEmployeeInfo = new MbOrgEmployeeInfo();
        mbOrgEmployeeInfo.setName(addUserInfoFrontRequest.getName());
        mbOrgEmployeeInfo.setEmail(addUserInfoFrontRequest.getEmail());
        mbOrgEmployeeInfo.setMobilePhone(addUserInfoFrontRequest.getPhoneNum());
        mbOrgEmployeeInfo.setValid(CommonConst.TRUE);
        mbOrgEmployeeInfo.setIsBackground(Boolean.FALSE);
        uid = UUID.randomUUID().toString();
        mbOrgEmployeeInfo.setUid(uid);
        mbOrgEmployeeInfo.setAreaCode(addUserInfoFrontRequest.getAreaCode());
        mbOrgEmployeeInfo.setGender("0".equals(addUserInfoFrontRequest.getSex()) ? "M" : "F");
        mbOrgEmployeeInfo.setNationality("CN|中国大陆");
        boolean flag = organizationEmployeeService.create(mbOrgEmployeeInfo);
        if (!flag) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.USER_CREATE_ERROR);
        }
        // 绑定兑换码
        redemptionCodeService.bindRedemptionCode(mbOrgEmployeeInfo.getUid(), mbOrgEmployeeInfo.getName());
        // 保存证件信息
        MbOrgUserIdcard mbOrgUserIdcard = new MbOrgUserIdcard();
        mbOrgUserIdcard.setCardType(Integer.valueOf(addUserInfoFrontRequest.getCardType()));
        mbOrgUserIdcard.setCardNo(addUserInfoFrontRequest.getCardNo());
        mbOrgUserIdcard.setEmployeeUid(uid);
        boolean cardFlag = organizationUserIdCardService.save(mbOrgUserIdcard);
        if (!cardFlag) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.SAVE_CARD_FAILED);
        }
        // 保存关系表。默认审批中状态
        MbUserOrgRelation mbUserOrgRelation = new MbUserOrgRelation();
        mbUserOrgRelation.setOrgId(addUserInfoFrontRequest.getOrgId());
        mbUserOrgRelation.setUid(uid);
        mbUserOrgRelation.setStatus(UserOrgRelationStatusEnum.NORMAL.getStatus());
        boolean relationFlag = userOrgRelationService.save(mbUserOrgRelation);
        if (!relationFlag) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.USER_CREATE_ERROR);
        }
        // 新增用户到新鲜度出行人表
        MbFreshPassenger mbFreshPassenger = new MbFreshPassenger();
        mbFreshPassenger.setEmployeeUid(uid);
        mbFreshPassenger.setOrgId(addUserInfoFrontRequest.getOrgId());
        mbFreshPassenger.setName(addUserInfoFrontRequest.getName());
        mbFreshPassenger.setFreshTime(new Date());
        mbFreshPassenger.setValid(Boolean.FALSE);
        freshPassengerService.save(mbFreshPassenger);
        // 添加员工到login服务
        MbUserLoginVo mbUserLoginVo = new MbUserLoginVo();
        mbUserLoginVo.setUid(uid);
        mbUserLoginVo.setUserName(addUserInfoFrontRequest.getName());
        mbUserLoginVo.setPhoneNum(addUserInfoFrontRequest.getPhoneNum());
        mbUserLoginVo.setCountryCode(addUserInfoFrontRequest.getAreaCode());
        mbUserLoginVo.setCardNo(addUserInfoFrontRequest.getCardNo());
        mbUserLoginVo.setAccountName(addUserInfoFrontRequest.getAreaCode() + addUserInfoFrontRequest.getPhoneNum());
        Boolean userFlag = userLoginService.saveOrUpdate(mbUserLoginVo, false);
        if (!userFlag) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.ACCOUNT_CREATE_ERROR);
        }
        return new JSONResult<>(true);
    }

    /**
     * 查询用户的登录身份信息的状态
     *
     * @param request request
     * @return status
     */
    @RequestMapping(value = "/findUserOrgRelationStatus")
    JSONResult<Integer> findUserOrgRelationStatus(@RequestBody @Valid FindUserOrgRelationStatusRequest request) {
        // 查询关系表
        MbUserOrgRelation mbUserOrgRelation = userOrgRelationService.find(request.getOrgId(), request.getUid());
        return new JSONResult<>(mbUserOrgRelation.getStatus());
    }

    /**
     * 组织架构/岗位—人员信息列表_设置为负责人
     *
     * @return Boolean
     */
    @RequestMapping(value = "/setUpLeader")
    JSONResult<Boolean> setUpLeader(@RequestBody @Valid SetUpLeaderRequest setUpLeaderRequest) {
        String orgId = setUpLeaderRequest.getOrgId();
        // 取消负责人：cancel，设置负责人：set
        String type = setUpLeaderRequest.getType();
        List<String> uids = setUpLeaderRequest.getUid();
        boolean flag = Boolean.FALSE;
        if ("set".equals(type)) {
            flag = userOrgRelationService.setUpLeader(orgId, uids);
        } else if ("cancel".equals(type)) {
            flag = userOrgRelationService.cancelSetUpLeader(orgId, uids);
        }
        return new JSONResult<>(flag);
    }

    /**
     * 改变用户的组织结构
     *
     * @param changeUserIdentity
     * @return
     */
    @RequestMapping(value = "/changeUserIdentity")
    JSONResult<Boolean> changeUserIdentity(@RequestBody @Valid ChangeUserIdentityRequest changeUserIdentity) {
        List<String> orgIds = changeUserIdentity.getOrgId();
        List<String> uids = changeUserIdentity.getUid();
        for (String orgId : orgIds) {
            // 组织结构信息
            MbOrgInfo mbOrgInfo = organizationInfoService.findByOrgId(orgId);
            // 如果组织结构禁用直接过滤
            if (mbOrgInfo.getValid().equals(CommonConst.FALSE)) {
                continue;
            }
            for (String uid : uids) {
                // 先查询用户是否存在，如果存在，不做处理
                MbUserOrgRelation dbData = userOrgRelationService.find(orgId, uid);
                if (dbData != null && !dbData.getStatus().equals(UserOrgRelationStatusEnum.LEAVE.getStatus())) {
                    continue;
                }
                // #1.账号已有的待审核的身份，不可选。
                if (dbData != null && dbData.getStatus().equals(UserOrgRelationStatusEnum.VERIFY.getStatus())) {
                    continue;
                }
                // #2.账号已有的审核拒绝的身份，可选。作为一个全新的身份添加。
                if (dbData != null && dbData.getStatus().equals(UserOrgRelationStatusEnum.REFUSE.getStatus())) {
                    userOrgRelationService.batchUpdateStatus(CollUtil.newArrayList(uid), orgId, UserOrgRelationStatusEnum.NORMAL.getStatus());
                    freshPassengerService.batchValid(CollUtil.newArrayList(uid), orgId);
                    continue;
                }
                // 账号已有的审核通过（在职）的身份，不可选。
                if (dbData != null && dbData.getStatus().equals(UserOrgRelationStatusEnum.NORMAL.getStatus())) {
                    continue;
                }
                // 账号已有的已离职（未删除）的身份，不可选。
                if (dbData != null && dbData.getStatus().equals(UserOrgRelationStatusEnum.LEAVE.getStatus())) {
                    continue;
                }
                // 插入数据
                MbUserOrgRelation mbUserOrgRelation = new MbUserOrgRelation();
                mbUserOrgRelation.setOrgId(orgId);
                mbUserOrgRelation.setUid(uid);
                mbUserOrgRelation.setStatus(UserOrgRelationStatusEnum.NORMAL.getStatus());
                boolean save = userOrgRelationService.save(mbUserOrgRelation);
                if (save) {
                    log.info("orgId:[{}],uid[{}]添加用户身份成功", orgId, uid);
                } else {
                    log.info("orgId:[{}],uid[{}]添加用户身份失败", orgId, uid);
                }
                // 查询用户信息
                MbOrgEmployeeInfo mbOrgEmployeeInfo = organizationEmployeeService.findByUid(uid);
                // 新增用户到新鲜度出行人表
                MbFreshPassenger mbFreshPassenger = new MbFreshPassenger();
                mbFreshPassenger.setEmployeeUid(uid);
                mbFreshPassenger.setOrgId(orgId);
                mbFreshPassenger.setName(mbOrgEmployeeInfo.getName());
                if (StrUtil.isNotBlank(mbOrgEmployeeInfo.getFirstEnName()) && StrUtil.isNotBlank(mbOrgEmployeeInfo.getLastEnName())) {
                    mbFreshPassenger.setEnName(mbOrgEmployeeInfo.getFirstEnName() + "/" + mbOrgEmployeeInfo.getLastEnName());
                }
                mbFreshPassenger.setFreshTime(new Date());
                mbFreshPassenger.setValid(false);
                freshPassengerService.save(mbFreshPassenger);
                log.info("新增身份,添加数据到出行人表成功orgId[{}],uid[{}]", orgId, uid);
            }
        }
        return new JSONResult<>(true);
    }

    /**
     * 组织架构/岗位—人员信息列表_查看员工详情
     *
     * @param getUserInfoRequest
     * @return
     */
    @RequestMapping("/getUserInfo")
    JSONResult<GetUserInfoResponse> getUserInfo(@RequestBody @Valid GetUserInfoRequest getUserInfoRequest, BaseUserInfo baseUserInfo) {
        String orgId = getUserInfoRequest.getOrgId();
        String uid = getUserInfoRequest.getUid();
        Boolean singleSignOn = getUserInfoRequest.getSingleSignOn();
        GetUserInfoResponse getUserInfoResponse = new GetUserInfoResponse();
        GetUserInfoResponse.PersonInfo personInfo = new GetUserInfoResponse.PersonInfo();
        // 查询用户信息
        MbOrgEmployeeInfo userInfo = organizationEmployeeService.findByUid(uid);
        if (userInfo == null) {
            return JSONResult.errorMsg("用户信息不存在");
        }
        // 查询用户证件信息
        List<MbOrgUserIdcard> cardList = organizationUserIdCardService.findByEmployeeUid(uid);
        MbOrgUserIdcard mbOrgUserIdcard = new MbOrgUserIdcard();
        if (CollUtil.isNotEmpty(cardList)) {
            cardList = cardList.stream().sorted((a, b) -> b.getDatachangeLasttime().compareTo(a.getDatachangeLasttime())).collect(Collectors.toList());
            List<GetUserInfoResponse.CardInfo> cardInfos = CollUtil.newArrayList();
            for (MbOrgUserIdcard orgUserIdcard : cardList) {
                GetUserInfoResponse.CardInfo cardInfo = new GetUserInfoResponse.CardInfo();
                cardInfo.setCardNo(orgUserIdcard.getCardNo());
                cardInfo.setCardType(orgUserIdcard.getCardType());
                cardInfos.add(cardInfo);
            }
            personInfo.setCardInfo(cardInfos);
        }
        personInfo.setEmail(userInfo.getEmail());
        personInfo.setId(userInfo.getUid());
        personInfo.setName(userInfo.getName());
        personInfo.setPhoneNum(userInfo.getMobilePhone());
        // 性别不能为空
        if (StrUtil.isNotEmpty(userInfo.getGender())) {
            personInfo.setSex(userInfo.getGender().equals(OrgEmployeeConst.MAN) ? "0" : "1");
        }
        personInfo.setAreaCode(userInfo.getAreaCode());
        getUserInfoResponse.setPersonInfo(personInfo);
        // 查询用户身份信息
        List<MbUserOrgRelation> list = userOrgRelationService.listByUid(uid);
        if (CollUtil.isNotEmpty(list)) {
            // 是否是后台员工
            List<String> orgIds = CollUtil.newArrayList();
            if (!baseUserInfo.getBgUser()) {
                orgIds = organizationInfoService.listAllDepartmentByOrgId(orgId);
            }
            List<GetUserInfoResponse.IdentityInfo> returnList = new ArrayList<>();
            for (MbUserOrgRelation mbUserOrgRelation : list) {
                // 待审核状态过滤掉
                if (StrUtil.equals(UserOrgRelationStatusEnum.VERIFY.getStatus().toString(), mbUserOrgRelation.getStatus().toString())) {
                    continue;
                }
                GetUserInfoResponse.IdentityInfo identityInfo = new GetUserInfoResponse.IdentityInfo();
                identityInfo.setOrgId(mbUserOrgRelation.getOrgId());
                MbPostInfo mbPostInfo = postService.find(mbUserOrgRelation.getPostId());
                identityInfo.setRank(mbPostInfo == null ? null : mbPostInfo.getName());
                // 查询用户角色
                GetUserRoleDetailRequest req = new GetUserRoleDetailRequest();
                req.setOrgId(mbUserOrgRelation.getOrgId());
                req.setUid(uid);
                GetUserRoleListResponse data = userService.getUserRoleDetail(req);
                List<GetUserRoleListInfo> userRoleListInfoList = data.getUserRoleListInfoList();
                if (CollUtil.isNotEmpty(userRoleListInfoList)) {
                    List<String> roleNameList = userRoleListInfoList.stream().map(GetUserRoleListInfo::getRoleName).collect(Collectors.toList());
                    identityInfo.setAdminName(roleNameList);
                }
                // 是否可以操作，如果是后台员工，默认都可以操作，如果不是，需要查询用户的所有组织权限，然后对比身份的orgid，判断是否有
                if (baseUserInfo.getBgUser()) {
                    identityInfo.setOperable(true);
                } else {
                    // 单点登录情况下只有自己的身份才能操作
                    identityInfo.setOperable(orgIds.contains(mbUserOrgRelation.getOrgId()));
                }
                // 组织路径
                String orgPath = organizationInfoService.findOrgPath(mbUserOrgRelation.getOrgId());
                identityInfo.setOrgPath(orgPath);
                identityInfo.setStatus(mbUserOrgRelation.getStatus());
                identityInfo.setIsLeader(mbUserOrgRelation.getIsLeader() != null && mbUserOrgRelation.getIsLeader() == 1);
                identityInfo.setUid(uid);
                returnList.add(identityInfo);
            }
            getUserInfoResponse.setIdentityInfo(returnList);
        }
        return new JSONResult<>(getUserInfoResponse);
    }

    /**
     * 查询组织结构下人，支持用户名模糊匹配
     *
     * @param listUserRequest
     */
    @RequestMapping("/listByOrgIdAndUserName")
    public JSONResult<ListUserResponse> listByOrgIdAndUserName(@RequestBody ListUserRequest listUserRequest, BaseUserInfo baseUserInfo) {
        ListUserResponse listUserResponse = new ListUserResponse();
        String name = listUserRequest.getName();
        String selectOrgId = listUserRequest.getSelectOrgId();
        String uid = listUserRequest.getUid();
        Integer pageNum = listUserRequest.getPageNum();
        Integer pageSize = listUserRequest.getPageSize();

        List<String> orgIds = CollUtil.newArrayList();
        if (StrUtil.isNotEmpty(selectOrgId)) {
            // case1:根据orgId找到org范围
            orgIds.add(selectOrgId);
        } else if (BOOKING_RELATION_ADD_USER.toString().equals(listUserRequest.getQueryScene())
            && organizationApollo.enableBookingRelationShowAllOrg()) {
            orgIds = organizationInfoService.listAll().stream().map(MbOrgInfo::getOrgId).collect(Collectors.toList());
        } else {
            // case2:如果selectOrgId为空，则根据用户的权限来查询org范围
            orgIds = organizationInfoService.listAllDepartmentByOrgId(listUserRequest.getOrgId());
        }
        IPage<MbOrgEmployeeInfo> employeeInfoListPage = organizationEmployeeService.pageByNameAndOrgIds(name, orgIds, UserOrgRelationStatusEnum.NORMAL.getStatus(), pageNum, pageSize);
        List<MbOrgEmployeeInfo> employeeInfoList = employeeInfoListPage.getRecords();
        listUserResponse.setTotalCount(employeeInfoListPage.getTotal());
        listUserResponse.setTotalPage((int) employeeInfoListPage.getPages());
        // 是否需要筛选审核通过的数据
        if (listUserRequest.getShowDisableEmployee() != null && !listUserRequest.getShowDisableEmployee()) {
            employeeInfoList = employeeInfoList.stream().filter(p -> Objects.equals(p.getStatus(), UserOrgRelationStatusEnum.NORMAL.getStatus())).collect(Collectors.toList());
        }
        if (CollUtil.isEmpty(employeeInfoList)) {
            listUserResponse.setData(CollUtil.newArrayList());
            return new JSONResult<>(listUserResponse);
        }
        List<ListUserResponse.ListUserInfo> returnList = new ArrayList<>();
        List<String> dbDrgIds = employeeInfoList.stream().filter(p -> StrUtil.isNotEmpty(p.getOrgId())).map(MbOrgEmployeeInfo::getOrgId).collect(Collectors.toList());
        List<MbOrgInfo> mbOrgInfoList = organizationInfoService.listByOrgIds(dbDrgIds);
        if (CollUtil.isEmpty(mbOrgInfoList)) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.ORG_INFO_IS_NULL);
        }
        Map<String, MbOrgInfo> orgInfoMap = mbOrgInfoList.stream().collect(Collectors.toMap(MbOrgInfo::getOrgId, mbOrgInfo -> mbOrgInfo));
        for (MbOrgEmployeeInfo mbOrgEmployeeInfo : employeeInfoList) {
            ListUserResponse.ListUserInfo listUserInfo = new ListUserResponse.ListUserInfo();
            listUserInfo.setDepartment(orgInfoMap.get(mbOrgEmployeeInfo.getOrgId()) == null ? null : orgInfoMap.get(mbOrgEmployeeInfo.getOrgId()).getName());
            listUserInfo.setEmail(mbOrgEmployeeInfo.getEmail());
            listUserInfo.setId(mbOrgEmployeeInfo.getUid());
            listUserInfo.setName(mbOrgEmployeeInfo.getName());
            listUserInfo.setOrgId(mbOrgEmployeeInfo.getOrgId());
            listUserInfo.setPhone(mbOrgEmployeeInfo.getMobilePhone());
            returnList.add(listUserInfo);
        }
        listUserResponse.setData(returnList);

        return new JSONResult<>(sortListUserResponse(listUserResponse, listUserRequest.getSortType()));
    }

    /**
     * 对查询出的用户根据姓名排序
     */
    private ListUserResponse sortListUserResponse(ListUserResponse listUserResponse, String sortType) {
        if (SortTypeEnum.BY_NAME_ASC.name().equals(sortType)) {
            Collator comparator = Collator.getInstance(Locale.CHINA);
            if (CollectionUtils.isEmpty(listUserResponse.getData())) {
                return listUserResponse;
            }
            listUserResponse.getData().sort((o1, o2) -> comparator.compare(o1.getName(), o2.getName()));
            return listUserResponse;
        }
        return listUserResponse;
    }

    /**
     * 组织架构/岗位—人员信息列表_编辑员工个人信息
     *
     * @param updateEmployeeRequest request
     * @return 是否成功
     */
    @RequestMapping("/updateEmployee")
    public JSONResult<Boolean> updateEmployee(@RequestBody @Valid UpdateEmployeeRequest updateEmployeeRequest) {
        String uid = updateEmployeeRequest.getUid();
        Integer cardType = updateEmployeeRequest.getCardType();
        String cardNo = updateEmployeeRequest.getCardNo();
        // 根据uid更新用户信息
        MbOrgEmployeeInfo mbOrgEmployeeInfo = new MbOrgEmployeeInfo();
        BeanUtils.copyProperties(updateEmployeeRequest, mbOrgEmployeeInfo);
        mbOrgEmployeeInfo.setGender("0".equals(updateEmployeeRequest.getGender()) ? "M" : "F");
        organizationEmployeeService.updateAll(mbOrgEmployeeInfo);
        // 证件信息如果存在，则再更新证件信息
        if (updateEmployeeRequest.getCardType() != null && StrUtil.isNotBlank(updateEmployeeRequest.getCardNo())) {
            MbOrgUserIdcard dbCard = organizationUserIdCardService.findByEmployeeUidAndType(updateEmployeeRequest.getUid(), updateEmployeeRequest.getCardType());
            if (dbCard == null) {
                // 新增
                MbOrgUserIdcard mbOrgUserIdcard = new MbOrgUserIdcard();
                mbOrgUserIdcard.setCardNo(cardNo);
                mbOrgUserIdcard.setCardType(cardType);
                mbOrgUserIdcard.setEmployeeUid(uid);
                organizationUserIdCardService.save(mbOrgUserIdcard);
            } else {
                // 修改
                MbOrgUserIdcard mbOrgUserIdcard = new MbOrgUserIdcard();
                BeanUtils.copyProperties(updateEmployeeRequest, mbOrgUserIdcard);
                mbOrgUserIdcard.setEmployeeUid(updateEmployeeRequest.getUid());
                organizationUserIdCardService.updateEmployeeCard(mbOrgUserIdcard);
            }
        }
        return new JSONResult<>(true);
    }

    @RequestMapping("getCardNo")
    @SuppressWarnings("unchecked")
    public JSONResult<String> getCardNo(@RequestParam String uid) {
        List<MbOrgUserIdcard> cardList = organizationUserIdCardService.findByEmployeeUid(uid);
        if (CollectionUtils.isNotEmpty(cardList)) {
            return JSONResult.success(cardList.get(0).getCardNo());
        }
        return new JSONResult<>(1000010, "当前用户没有证件", null);
    }

    /**
     * 姓名和员工编号模糊匹配
     * 前端接口
     * 契约文档：http://mdoc.uat.qa.nt.ctripcorp.com:9526/project/11/interface/api/836
     * url：http://localhost:7890/employee/searchAllEmpList
     *
     * @param request
     * @return 员工列表
     */
    @RequestMapping("/searchAllEmpList")
    @ResponseBody
    public JSONResult<List<SearchAllEmpListResponse>> searchAllEmpList(@RequestBody SearchAllEmpListRequest request, HttpServletRequest httpRequest) {
        String uid = httpRequest.getParameter("uId");
        String userName = httpRequest.getParameter("userName");
        // todo 根据uid判断用户权限，需要实现
        String query = request.getQuery();
        String orgId = request.getId();
        String postOrgId = request.getOrgId();
        Long postId = request.getPosId();
        boolean isPost = false;
        if (StringUtils.isNotBlank(postOrgId)) {
            isPost = true;
        }
        // 接口支持全集团查询类型
        boolean findWholeGroup = WholeGroupQueryEnum.APPROVE.getCode().equals(request.getWholeGroupQuery())
                && organizationApollo.enableApproveShowAllOrg();
        if(findWholeGroup){
            List<SearchAllEmpListResponse> returnList = this.getSearchAllEmpListResponses(request);
            return new JSONResult<>(returnList);
        }
        // 查询组织架构
        if (!isPost) {
            List<SearchAllEmpListResponse> searchAllEmpListResponses = searchOrgAllEmpList(uid, query, orgId);
            return new JSONResult<>(searchAllEmpListResponses);
        } else {
            // 查询岗位
            List<SearchAllEmpListResponse> searchAllEmpListResponses = searchPostAllEmpList(postOrgId, query, postId);
            return new JSONResult<>(searchAllEmpListResponses);
        }
    }

    private List<SearchAllEmpListResponse> getSearchAllEmpListResponses(SearchAllEmpListRequest request) {
        List<SearchAllEmpListResponse> returnList = new ArrayList<>();
        List<MbOrgEmployeeInfo> list = organizationEmployeeService.listByName(request.getQuery());
        List<String> uidList = list.stream().map(MbOrgEmployeeInfo::getUid).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(uidList)){
            return returnList;
        }
        List<MbUserOrgRelation> mbUserOrgRelations = userOrgRelationMapper.listByUids(uidList);
        Map<String,String> uidOrgIdMap = mbUserOrgRelations.stream().collect(Collectors.toMap(MbUserOrgRelation::getUid,MbUserOrgRelation::getOrgId));
        for (MbOrgEmployeeInfo mbOrgEmployeeInfo : list) {
            mbOrgEmployeeInfo.setOrgId(uidOrgIdMap.get(mbOrgEmployeeInfo.getUid()));
        }
        // 先拿到部门名称
        List<String> orgIds = mbUserOrgRelations.stream()
                .filter(p -> StringUtils.isNotBlank(p.getOrgId()))
                .map(MbUserOrgRelation::getOrgId)
                .distinct()
                .collect(Collectors.toList());
        List<MbOrgInfo> mbOrgInfoList = organizationInfoService.listNameByOrgIds(orgIds);
        if(CollectionUtils.isEmpty(mbOrgInfoList)){
            return returnList;
        }
        // 转成map，之后组装返回数据
        Map<String, String> orgNameMap = mbOrgInfoList.stream()
                .filter(p -> StringUtils.isNotBlank(p.getName()))
                .collect(Collectors.toMap(MbOrgInfo::getOrgId, MbOrgInfo::getName));
        for (MbOrgEmployeeInfo mbOrgEmployeeInfo : list) {
            SearchAllEmpListResponse searchAllEmpListResponse = new SearchAllEmpListResponse();
            searchAllEmpListResponse.setLabel(mbOrgEmployeeInfo.getName());
            searchAllEmpListResponse.setStatus("0");
            if (orgNameMap.size() > 0) {
                searchAllEmpListResponse.setDepartment(orgNameMap.get(mbOrgEmployeeInfo.getOrgId()));
            }
            searchAllEmpListResponse.setId(mbOrgEmployeeInfo.getUid());
            searchAllEmpListResponse.setOrgId(mbOrgEmployeeInfo.getOrgId());
            searchAllEmpListResponse.setUid(mbOrgEmployeeInfo.getUid());
            returnList.add(searchAllEmpListResponse);
        }
        return returnList;
    }

    private List<SearchAllEmpListResponse> searchOrgAllEmpList(String uid, String query, String orgId) {
        // 根据uid判断权限
        boolean backgroundUser = organizationEmployeeService.isBackgroundUser(uid);
        List<MbOrgEmployeeInfo> list = new ArrayList<>();
        if (backgroundUser) {
            list = organizationEmployeeService.listByName(query);
        } else {
            List<String> orgIds = organizationInfoService.listAllChildOrgIdsByOrgId(orgId);
            list = organizationEmployeeService.listByNameAndOrgIds(query, orgIds, null, null, null);
        }
        List<SearchAllEmpListResponse> returnList = new ArrayList<>();

        if (CollectionUtils.isEmpty(list)) {
            return returnList;
        }
        // 先拿到部门名称
        List<String> orgIds = list.stream()
                .filter(p -> StringUtils.isNotBlank(p.getOrgId()))
                .map(MbOrgEmployeeInfo::getOrgId)
                .distinct()
                .collect(Collectors.toList());
        List<MbOrgInfo> mbOrgInfoList = organizationInfoService.listNameByOrgIds(orgIds);
        // 转成map，之后组装返回数据
        Map<String, String> orgNameMap = mbOrgInfoList.stream()
                .filter(p -> StringUtils.isNotBlank(p.getName()))
                .collect(Collectors.toMap(MbOrgInfo::getOrgId, MbOrgInfo::getName));
        for (MbOrgEmployeeInfo mbOrgEmployeeInfo : list) {
            SearchAllEmpListResponse searchAllEmpListResponse = new SearchAllEmpListResponse();
            searchAllEmpListResponse.setLabel(mbOrgEmployeeInfo.getName());
            searchAllEmpListResponse.setStatus(mbOrgEmployeeInfo.getOrgId().equals(orgId) ? "1" : "0");
            if (orgNameMap.size() > 0) {
                searchAllEmpListResponse.setDepartment(orgNameMap.get(mbOrgEmployeeInfo.getOrgId()));
            }
            searchAllEmpListResponse.setId(mbOrgEmployeeInfo.getUid());
            searchAllEmpListResponse.setOrgId(mbOrgEmployeeInfo.getOrgId());
            searchAllEmpListResponse.setUid(mbOrgEmployeeInfo.getUid());
            returnList.add(searchAllEmpListResponse);
        }
        return returnList;
    }

    private List<SearchAllEmpListResponse> searchPostAllEmpList(String postOrgId, String query, Long postId) {
        List<SearchAllEmpListResponse> returnList = new ArrayList<>();
        //查询最近的公司
        MbOrgInfo mbOrgInfo = organizationInfoService.findRecentCompanyIdByOrgId(postOrgId);
        if (mbOrgInfo == null) {
            return returnList;
        }
        postOrgId = mbOrgInfo.getOrgId();
        //查询该公司下的子部门，穿透子公司
        List<String> orgIds = organizationInfoService.listAllDepartmentIds(postOrgId, false,true);
        orgIds.add(postOrgId);
        // 查询员工
        List<MbOrgEmployeeInfo> list = organizationEmployeeService.listByNameAndOrgIds(query, orgIds, UserOrgRelationStatusEnum.NORMAL.getStatus(), null, null);
        if (CollectionUtils.isEmpty(list)) {
            return returnList;
        }
        // 先拿到部门名称
        List<String> userOrgIds = list.stream()
                .filter(p -> StringUtils.isNotBlank(p.getOrgId()))
                .map(MbOrgEmployeeInfo::getOrgId)
                .distinct()
                .collect(Collectors.toList());
        List<MbOrgInfo> mbOrgInfoList = organizationInfoService.listNameByOrgIds(userOrgIds);
        // 转成map，之后组装返回数据
        Map<String, String> orgNameMap = mbOrgInfoList.stream()
                .filter(p -> StringUtils.isNotBlank(p.getName()))
                .collect(Collectors.toMap(MbOrgInfo::getOrgId, MbOrgInfo::getName));
        for (MbOrgEmployeeInfo mbOrgEmployeeInfo : list) {
            SearchAllEmpListResponse searchAllEmpListResponse = new SearchAllEmpListResponse();
            searchAllEmpListResponse.setLabel(mbOrgEmployeeInfo.getName());
            Long userPostId = mbOrgEmployeeInfo.getPostId();
            if (userPostId == null) {
                searchAllEmpListResponse.setStatus("0");
            } else {
                searchAllEmpListResponse.setStatus(mbOrgEmployeeInfo.getPostId().equals(postId) ? "1" : "0");
            }
            if (orgNameMap != null && orgNameMap.size() > 0) {
                searchAllEmpListResponse.setDepartment(orgNameMap.get(mbOrgEmployeeInfo.getOrgId()));
            }
            searchAllEmpListResponse.setId(mbOrgEmployeeInfo.getUid());
            searchAllEmpListResponse.setOrgId(mbOrgEmployeeInfo.getOrgId());
            searchAllEmpListResponse.setUid(mbOrgEmployeeInfo.getUid());
            returnList.add(searchAllEmpListResponse);
        }
        return returnList;
    }

    /**
     * 通过部门id/岗位id查询部门下所有员工信息
     * 前端接口
     * 契约文档：http://10.5.119.87:9526/project/11/interface/api/566
     * url：http://localhost:7890/employee/getEmpInDepart
     *
     * @param request id（部门id）
     * @return 员工列表
     */
    @RequestMapping("/getEmpInDepart")
    @ResponseBody
    public JSONResult<List<DepartmentEmployeeVo>> getEmpInDepart(@RequestBody ListEmployeeRequest request) {
        List<DepartmentEmployeeVo> returnList = new ArrayList<>();
        // 左侧部门id
        String currentId = request.getOrgId();
        // 右边部门id
        String rightId = request.getId();
        // 组织架构类型（岗位：P 部门：D）
        String type = request.getType();

        List<MbOrgInfo> depList = organizationInfoService.findMbOrgInfoByOrgId(currentId, null);
        if (CollectionUtils.isNotEmpty(depList)) {
            // 封装所有部门数据
            // 封装这个部门下的人
            for (MbOrgInfo mbOrgInfo : depList) {
                DepartmentEmployeeVo departmentEmployeeVo = new DepartmentEmployeeVo();
                departmentEmployeeVo.setDepartment(mbOrgInfo.getOrgId());
                departmentEmployeeVo.setLabel(mbOrgInfo.getName());
                departmentEmployeeVo.setId(mbOrgInfo.getOrgId());
                departmentEmployeeVo.setType(mbOrgInfo.getOrgType());
                returnList.add(departmentEmployeeVo);
            }
        }
        // 查询部门下所有人
        List<MbOrgEmployeeInfo> list = organizationEmployeeService.listAllByDepartmentIdAndName(currentId, null);
        if (CollectionUtils.isEmpty(list)) {
            return new JSONResult<>(returnList);
        }
        List<String> orgIds = list.stream().map(MbOrgEmployeeInfo::getOrgId).distinct().collect(Collectors.toList());
        // 查询所有部门名称
        List<MbOrgInfo> nameList = organizationInfoService.listNameByOrgIds(orgIds);
        Map<String, String> nameMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(nameList)) {
            nameMap = nameList.stream().collect(Collectors.toMap(MbOrgInfo::getOrgId, MbOrgInfo::getName));
        }
        for (MbOrgEmployeeInfo mbOrgEmployeeInfo : list) {
            DepartmentEmployeeVo departmentEmployeeVo = new DepartmentEmployeeVo();
            departmentEmployeeVo.setId(mbOrgEmployeeInfo.getUid());
            departmentEmployeeVo.setLabel(mbOrgEmployeeInfo.getName());
            departmentEmployeeVo.setOrgId(mbOrgEmployeeInfo.getOrgId());
            // type = D
            if (StrUtil.isNotBlank(rightId)) {
                if ("D".equals(type)) {
                    departmentEmployeeVo.setStatus(rightId.equals(mbOrgEmployeeInfo.getOrgId()) ? 1 : 0);
                    // type = P
                } else if ("P".equals(type)) {
                    departmentEmployeeVo.setStatus(Long.valueOf(rightId).equals(mbOrgEmployeeInfo.getPostId()) ? 1 : 0);
                }
            } else {
                departmentEmployeeVo.setStatus(0);
            }
            if (MapUtils.isNotEmpty(nameMap)) {
                departmentEmployeeVo.setDepartment(nameMap.get(mbOrgEmployeeInfo.getOrgId()));
            }
            returnList.add(departmentEmployeeVo);
        }
        return new JSONResult<>(returnList);
    }

    /**
     * 删除用户
     */
    @RequestMapping("/deleteUser")
    public JSONResult<Boolean> deleteUser(@RequestParam(name = "uid") String uid) {
        // 删除用户信息
        organizationEmployeeService.deleteByUid(uid);
        // 删除用户所有身份
        userOrgRelationService.deleteByUid(uid);
        // 删除代订
        UidOrgIdEntry index = new UidOrgIdEntry();
        index.setUid(uid);
        bookingRelationService.updateStatus(index, MbBookingRelationVo.STATUS_DELETED, Arrays.asList(MbBookingRelationVo.STATUS_DISABLE, MbBookingRelationVo.STATUS_ENABLE));
        // 删除用户出行人
        freshPassengerService.deleteEmployee(uid, null);
        // 删除出行人非员工信息
        freshPassengerService.deleteNonEmployeeByUid(uid);
        // 删除用户的非员工信息
        organizationNonEmployeeService.deleteByUid(uid);
        // 删除用户证件
        organizationUserIdCardService.deleteByEmployeeUid(uid);
        return new JSONResult<>(true);
    }


    /**
     * 人员操作 新增
     *
     * @param request 人员信息
     * @return 操作结果
     */
    @OperateLog(ChooseBusinesstype.ORGSTRUCTURELIST)
    @RequestMapping("/saveEmpBaseInfo")
    @ResponseBody
    public JSONResult<SaveEmpBaseInfoResponse> saveEmpBaseInfo(@RequestBody OperateEmployeeRequest request, BaseUserInfo baseUserInfo) {
        JSONResult<SaveEmpBaseInfoResponse> result = transactionTemplate.execute(status -> {
            JSONResult<SaveEmpBaseInfoResponse> empResult = saveEmpInfo(request, baseUserInfo);
            return empResult;
        });

        // 人员操作成功，发送开卡消息
        if(Objects.nonNull(result) && Objects.nonNull(result.getData()) && result.getData().getFlag()) {
            String empStatus = null;
            // 新增
            if (0 == request.getStatus()) {
                empStatus = EmployeeActionEvent.OpenCardAction.ACTION_ADD;
            } else if(1 == request.getStatus()) {
                empStatus =  EmployeeActionEvent.OpenCardAction.ACTION_UPDATE;
            } else if (2 == request.getStatus()) {
                empStatus =  EmployeeActionEvent.OpenCardAction.ACTION_DELETE;
            }
            // 发送开卡消息通知
            eventCenter.post(new EmployeeActionEvent(Lists.newArrayList(request.getUid()), request.getOrgId(), empStatus));
        }
        return result;
    }

    /**
     * 人员中文姓名、英文名，英文性、手机号、工号、证件号、邮箱的输入框不可输入空格
     */
    private void trimRequestParams(OperateEmployeeRequest request) {
        BiConsumer<String, Consumer<String>> biConsumer = (s, consumer) -> {
            if (StringUtils.isNotBlank(s)) {
                // 去除首中尾空格
                consumer.accept(org.springframework.util.StringUtils.trimAllWhitespace(s));
            }
        };

        biConsumer.accept(request.getFirstName(), request::setFirstName);
        biConsumer.accept(request.getLastName(), request::setLastName);
        biConsumer.accept(request.getSurname(), request::setSurname);
        biConsumer.accept(request.getGivenname(), request::setGivenname);
        biConsumer.accept(request.getFullEnName(), request::setFullEnName);
        biConsumer.accept(request.getFullName(), request::setFullName);
        biConsumer.accept(request.getUserName(), request::setUserName);
        biConsumer.accept(request.getTelPhone(), request::setTelPhone);
        biConsumer.accept(request.getUid(), request::setUid);
        biConsumer.accept(request.getMailbox(), request::setMailbox);

        // 证件信息
        Optional.ofNullable(request.getcInfo())
                .ifPresent(cInfo -> cInfo.forEach(userIdCardFrontVo -> {
                            if (StringUtils.isNotBlank(userIdCardFrontVo.getcNumber())) {
                                userIdCardFrontVo.setcNumber(userIdCardFrontVo.getcNumber().trim());
                            }
                        })
                );


    }

    public JSONResult<SaveEmpBaseInfoResponse> saveEmpInfo(OperateEmployeeRequest request, BaseUserInfo baseUserInfo) {
        checkRequestParams(request);
        Integer status = request.getStatus();

        // 等于0表示新增，1表示修改，2表示删除。只有新增时才去除空格
        if (status == 0) {
            ObjectStringTrimUtils.allFieldRemoveWarp(request);
        }
        log.info("request:{}", JsonUtils.toJsonString(request));

        // 人员中文姓名、英文名，英文性、手机号、工号、证件号、邮箱的输入框不可输入空格
        //trimRequestParams(request);

        MbOrgEmployeeInfo mbOrgEmployeeInfo = new MbOrgEmployeeInfo();
        // uid去掉空格
        String uid = request.getUid();
        mbOrgEmployeeInfo.setName(request.getUserName());
        if (StringUtils.isBlank(request.getUserName())) {
            throw new CorpBusinessException(ExceptionCodeEnum.Alert, "请填写员工姓名");
        }
        mbOrgEmployeeInfo.setUid(uid);
        if(StringUtils.isNotBlank(request.getFirstName()) && StringUtils.isNotBlank(request.getLastName())){
            mbOrgEmployeeInfo.setLastEnName(request.getLastName());
            mbOrgEmployeeInfo.setFirstEnName(request.getFirstName());
        }else if(StringUtils.isNotBlank(request.getSurname()) && StringUtils.isNotBlank(request.getGivenname())){
            mbOrgEmployeeInfo.setFirstEnName(request.getGivenname());
            mbOrgEmployeeInfo.setLastEnName(request.getSurname());
        }else{
            log.error("firstName,lastName error:{},{},{},{}",
                    request.getFirstName() ,request.getLastName(),request.getSurname() ,request.getGivenname());
        }
        mbOrgEmployeeInfo.setMobilePhone(request.getTelPhone());
        mbOrgEmployeeInfo.setAreaCode(request.getAreaCode());
        mbOrgEmployeeInfo.setEmail(request.getMailbox());
        mbOrgEmployeeInfo.setCreditCardNumbers(request.getCreditCardNumbers());
        mbOrgEmployeeInfo.setEmployeeType(Objects.isNull(request.getEmployeeType()) ? 0 : request.getEmployeeType());
        mbOrgEmployeeInfo.setCorporateEntity(request.getCorporateEntity());
        NameInfoBo nameInfoBo = JsonUtils.parse(JsonUtils.toJsonString(request),NameInfoBo.class);
        nameInfoBo.setFullEnName(com.corpgovernment.organization.util.StrUtils.processFullEnName(nameInfoBo.getSurname(),nameInfoBo.getGivenname()));
        if(StrUtils.checkNameInfo(nameInfoBo)){
            mbOrgEmployeeInfo.setNameInfo(JsonUtils.toJsonString(nameInfoBo));
        }
        String gender = request.getGender();
        if (StringUtils.isNotBlank(gender)) {
            mbOrgEmployeeInfo.setGender(request.getGender().equals("0") ? CommonConst.MAN : CommonConst.FEMALE);
        }
        mbOrgEmployeeInfo.setNationality(request.getNationality());
        mbOrgEmployeeInfo.setBirthday(request.getBirthday());
        String state = request.getState();
        if (StringUtils.isNotBlank(state)) {
            if (state.equals("0")) {
                mbOrgEmployeeInfo.setValid(CommonConst.TRUE);
            } else if (state.equals("1")) {
                mbOrgEmployeeInfo.setValid(CommonConst.FALSE);
            }
        } else {
            mbOrgEmployeeInfo.setValid(CommonConst.TRUE);
        }

        boolean flag = false;
        // 新增
        if (0 == status) {
            UserLoginRequest userLoginRequest = new UserLoginRequest();
            userLoginRequest.setPhoneNum(request.getTelPhone());
            userLoginRequest.setCountryCode(request.getAreaCode());
            MbUserLogin userLogin = userLoginService.getByPhoneNumAndCountryCodeAndBgUser(userLoginRequest.getPhoneNum(), userLoginRequest.getCountryCode(), false);
            // 账号是否存在
            boolean ifExist = Boolean.FALSE;
            // 账号是否禁用
            boolean enabled = Boolean.TRUE;
            //是否覆盖
            boolean isCover = request.getIsCover();
            if (userLogin != null) {
                ifExist = true;
                enabled = userLogin.getStatus() == 1;
            }
            //账号被停用，不允许添加。
            if (!enabled) {
                throw new CorpBusinessException(OrganizationResponseCodeEnum.PARENT_ORG_VALID);
            }
            if (ifExist) {
                //判断人员信息是否一致
                MbOrgEmployeeInfo exitedUser = organizationEmployeeService.findByUid(userLogin.getUid());
                if (exitedUser == null) {
                    throw new CorpBusinessException(OrganizationResponseCodeEnum.USER_ALREADY_EXISTS);
                }
                boolean baseEmpInfoFlag = adjustBaseEmpInfo(exitedUser, request);
                log.info("查询到的人员信息是：{}", JsonUtils.toJsonString(exitedUser));
                //查询关联的组织信息
                List<MbUserOrgRelation> mbUserOrgRelations = userOrgRelationService.listByUid(userLogin.getUid());
                if (CollectionUtils.isNotEmpty(mbUserOrgRelations)) {
                    String orgStr = null;
                    for (MbUserOrgRelation mbUserOrgRelation : mbUserOrgRelations) {
//                        if (mbUserOrgRelation.getOrgId().equals(request.getOrgId())) {
//                            return JSONResult.errorMsg("当前组织下已存在相同手机号的账号,无法继续添加");
//                        }
                        if (!mbUserOrgRelation.getOrgId().equals(request.getOrgId()) && baseEmpInfoFlag) {
                            baseEmpInfoFlag = false;
                        }
                        List<OrgInfoVo> orgInfoList = organizationInfoService.getOrgInfoList(mbUserOrgRelation.getOrgId(), true);
                        StringBuffer orgBuffer = new StringBuffer();
                        orgInfoList = orgInfoList.stream().sorted(Comparator.comparing(OrgInfoVo::getLevel))
                                .collect(Collectors.toList());
                        if (!CollectionUtils.isEmpty(orgInfoList)) {
                            for (OrgInfoVo orgInfoVo : orgInfoList) {
                                orgBuffer.append(orgInfoVo.getName()).append(">");
                            }
                            orgStr = orgBuffer.substring(0, orgBuffer.length() - 1).concat(" ").concat(userLogin.getUserName()).concat("\n");
                        }
                    }
                    if (!baseEmpInfoFlag && !isCover) {
                        //账号在系统内其他组织中拥有身份信息
                        return JSONResult.success(new SaveEmpBaseInfoResponse(false, 2, orgStr, userLogin.getUid()));
                    } else {
                        //先删除员工信息
                        organizationEmployeeService.deleteByUid(userLogin.getUid());
                        //删除原有证件
                        organizationUserIdCardService.deleteByEmployeeUid(userLogin.getUid());
                        // 先删除用户常旅客卡，然后再插入现有证件
                        organizationUserFfpService.deleteByUid(userLogin.getUid());
                        //删除其余身份信息
                        userOrgRelationService.deleteByUid(userLogin.getUid());
                    }
                } else {
                    //人员信息不一致，无身份
                    if (!baseEmpInfoFlag) {
                        return JSONResult.success(new SaveEmpBaseInfoResponse(false, 2, null, userLogin.getUid()));
                    }
                    MbFreshPassenger record = new MbFreshPassenger();
                    record.setEmployeeUid(userLogin.getUid());
                    record.setOrgId(request.getOrgId());
                    record.setIsDeleted(false);
                    freshPassengerService.updateByRecord(record);
                    log.info("添加用户成功，修改用户组织有效用uid:{},orgId:{}", userLogin.getUid(), request.getOrgId());
                    tokenValidUtil.updateUserOrgTokenValid(userLogin.getUid(), request.getOrgId(), true);
                    //账号在系统内其他组织中无身份信息
                    return JSONResult.success(new SaveEmpBaseInfoResponse(false, 1, null, userLogin.getUid()));
                }
            }
            // 判断uid是否存在
            MbOrgEmployeeInfo dbUser = organizationEmployeeService.findByUid(uid);
            if (dbUser != null && StringUtils.isNotBlank(dbUser.getName())) {
                throw new CorpBusinessException(OrganizationResponseCodeEnum.USER_ALREADY_EXISTS);
            }
            if (StringUtils.isBlank(uid)) {
                uid = UUID.randomUUID().toString();
            }
            mbOrgEmployeeInfo.setUid(uid);
            // 新增用户
            MbOrgEmployeeInfo record = new MbOrgEmployeeInfo();
            record.setIsBackground(false);
            record.setMobilePhone(mbOrgEmployeeInfo.getMobilePhone());
            record.setAreaCode(mbOrgEmployeeInfo.getAreaCode());
            record.setDeleteTime(new Date(0));
            MbOrgEmployeeInfo oldEmployeeInfo = mbOrgEmployeeLoader.selectOneByRecord(record);
            if (oldEmployeeInfo != null) {
                throw new CorpBusinessException(OrganizationResponseCodeEnum.EMPLOYEE_PHONE_NO_EXIST);
            }
            flag = organizationEmployeeService.create(mbOrgEmployeeInfo);

            // 绑定兑换码
            redemptionCodeService.bindRedemptionCode(mbOrgEmployeeInfo.getUid(), mbOrgEmployeeInfo.getName());

            // 新增有效证件
            List<UserIdCardFrontVo> cardList = request.getcInfo();
            if (CollectionUtils.isNotEmpty(cardList)) {
                List<MbOrgUserIdcard> mbOrgUserIdcardList = new ArrayList<>();
                MbOrgUserIdcard mbOrgUserIdcard = null;
                Date date = new Date();
                for (UserIdCardFrontVo userIdCardFrontVo : cardList) {
                    mbOrgUserIdcard = new MbOrgUserIdcard();
                    mbOrgUserIdcard.setCardType(userIdCardFrontVo.getCtype());
                    mbOrgUserIdcard.setCardNo(userIdCardFrontVo.getcNumber());
                    mbOrgUserIdcard.setTimeLimit(userIdCardFrontVo.getcDate());
                    if (StringUtils.isNotBlank(userIdCardFrontVo.getPlaceOfIssue())) {
                        mbOrgUserIdcard.setPlaceOfIssue(userIdCardFrontVo.getPlaceOfIssue());
                    }
                    mbOrgUserIdcard.setEmployeeUid(uid);
//                    mbOrgUserIdcard.setDeleted(false);
                    mbOrgUserIdcard.setDeleteTime(new Date(0));
                    mbOrgUserIdcard.setDatachangeCreatetime(date);
                    mbOrgUserIdcard.setDatachangeLasttime(date);
                    //检查证件是否重复，重复判断依据是 type+number唯一
                    List<MbOrgUserIdcard> cards = organizationUserIdCardService.findByTypeAndNo(
                        Integer.valueOf(userIdCardFrontVo.getCtype()), userIdCardFrontVo.getcNumber(), false);
                    if (CollUtil.isNotEmpty(cards)) {
                        throw new CorpBusinessException(OrganizationResponseCodeEnum.CARD_EXISTS);
                    }
                    mbOrgUserIdcardList.add(mbOrgUserIdcard);
                }
                organizationUserIdCardService.saveList(mbOrgUserIdcardList);
            }
            // 新增常旅客
            List<UserFfpFrontVo> ffpList = request.getClkInfo();
            if (CollectionUtils.isNotEmpty(ffpList)) {
                List<MbOrgUserFfpinfo> userFfpFrontVoList = new ArrayList<>();
                MbOrgUserFfpinfo mbOrgUserFfpinfo = null;
                Date date = new Date();
                for (UserFfpFrontVo userFfpFrontVo : ffpList) {
                    if (StringUtils.isNotBlank(userFfpFrontVo.getHkNumber()) && StringUtils.isNotBlank(userFfpFrontVo.getClkCode())) {
                        mbOrgUserFfpinfo = new MbOrgUserFfpinfo();
                        mbOrgUserFfpinfo.setAirline(userFfpFrontVo.getHkNumber());
                        mbOrgUserFfpinfo.setFfpno(userFfpFrontVo.getClkCode());
                        mbOrgUserFfpinfo.setUid(uid);
                        mbOrgUserFfpinfo.setIsDeleted(false);
                        mbOrgUserFfpinfo.setDatachangeCreatetime(date);
                        mbOrgUserFfpinfo.setDatachangeLasttime(date);
                        userFfpFrontVoList.add(mbOrgUserFfpinfo);
                    }
                }
                if (!CollectionUtils.isEmpty(userFfpFrontVoList)) {
                    organizationUserFfpService.saveList(userFfpFrontVoList);
                }
            }

            // 新增用户到新鲜度出行人表
            MbFreshPassenger mbFreshPassenger = new MbFreshPassenger();
            mbFreshPassenger.setEmployeeUid(uid);
            mbFreshPassenger.setOrgId(request.getOrgId());
            mbFreshPassenger.setName(request.getUserName());
            String enName = "";
            if (StringUtils.isNotBlank(request.getFirstName()) || StringUtils.isNotBlank(request.getLastName())) {
                enName = (StringUtils.isNotBlank(request.getFirstName()) ? request.getFirstName() : "") + "/" + (StringUtils.isNotBlank(request.getLastName()) ? request.getLastName() : "");
            }
            mbFreshPassenger.setEnName(enName);
            mbFreshPassenger.setFreshTime(new Date());
            if (StringUtils.isNotBlank(state)) {
                if (state.equals("0")) {
                    mbFreshPassenger.setValid(false);
                } else if (state.equals("1")) {
                    mbFreshPassenger.setValid(true);
                }
            } else {
                mbFreshPassenger.setValid(false);
            }
            freshPassengerService.save(mbFreshPassenger);
            //新增常旅
            MbFreshPassengerRelation mbFreshPassengerRelation = new MbFreshPassengerRelation();
            mbFreshPassengerRelation.setEmployeeFlag(1);
            mbFreshPassengerRelation.setFreshUid(uid);
            mbFreshPassengerRelation.setFreshTime(new Date());
            mbFreshPassengerRelation.setIsDeleted(false);
            mbFreshPassengerRelation.setUid(uid);
            mbFreshPassengerRelation.setDatachangeLasttime(new Date());
            mbFreshPassengerRelation.setDatachangeCreatetime(new Date());
            freshPassengerRelationService.save(mbFreshPassengerRelation);
            //删除原有信息
            userOrgRelationService.deleteByUid(uid);
            //新增身份
            MbUserOrgRelation mbUserOrgRelation = new MbUserOrgRelation();
            mbUserOrgRelation.setOrgId(request.getOrgId());
            mbUserOrgRelation.setUid(uid);
            mbUserOrgRelation.setStatus(UserOrgRelationStatusEnum.NORMAL.getStatus());
            mbUserOrgRelation.setIsLeader(0);
            mbUserOrgRelation.setPostId(null);
            mbUserOrgRelation.setVipLevel(0);
            userOrgRelationService.save(mbUserOrgRelation);
            // 添加员工到login服务
            if (isCover) {
                userLogin.setUid(uid);
                userLoginService.updateUserLogin(userLogin, isCover);
            } else {
                MbUserLoginVo mbUserLoginVo = new MbUserLoginVo();
                mbUserLoginVo.setUid(uid);
                mbUserLoginVo.setUserName(request.getUserName());
                mbUserLoginVo.setPhoneNum(request.getTelPhone());
                mbUserLoginVo.setCountryCode(request.getAreaCode());
                mbUserLoginVo.setAccountName(request.getAreaCode() + request.getTelPhone());
                mbUserLoginVo.setCardNo(request.getcInfo().get(0).getcNumber());
                mbUserLoginVo.setEmail(request.getMailbox());
                Boolean userFlag = userLoginService.saveOrUpdate(mbUserLoginVo, false,request.getIsSyncLoginPhone());
                if (!userFlag) {
                    throw new CorpBusinessException(OrganizationResponseCodeEnum.USER_CREATE_ERROR);
                }
            }
            if (Objects.nonNull(request.getRoleId()) && request.getRoleId() > 0) {
                UidOrgIdEntry identity = new UidOrgIdEntry();
                identity.setUid(uid);
                identity.setOrgId(request.getOrgId());
                userRoleService.clearLeft(Collections.singleton(new UidOrgIdEntry(uid, request.getOrgId())));
                userRoleService.insertOrUpdate(null, identity, request.getRoleId());
            }
            // 修改
        } else if (1 == status) {
            // 查询员工原来的信息
            MbOrgEmployeeInfo dbUser = organizationEmployeeService.findByUid(uid);
            if (dbUser == null) {
                throw new CorpBusinessException(OrganizationResponseCodeEnum.USER_ALREADY_EXISTS);
            }
            boolean nameIsDiff = !dbUser.getName().equals(mbOrgEmployeeInfo.getName());
            MbOrgEmployeeInfo record = new MbOrgEmployeeInfo();
            record.setIsBackground(false);
            record.setMobilePhone(request.getTelPhone());
            record.setAreaCode(request.getAreaCode());
            MbOrgEmployeeInfo exitedEmp = mbOrgEmployeeLoader.selectOneByRecord(record);
            //校验手机号
            if (exitedEmp != null && !exitedEmp.getUid().equals(uid)) {
                throw new CorpBusinessException(OrganizationResponseCodeEnum.PHONE_EXISTS, request.getTelPhone());
            }
            // 编辑用户
            flag = organizationEmployeeService.updateAll(mbOrgEmployeeInfo);

            // 先删除用户证件，然后再插入现有证件
            boolean b1 = organizationUserIdCardService.deleteByEmployeeUid(uid);
            List<UserIdCardFrontVo> cardList = request.getcInfo();
            if (CollectionUtils.isNotEmpty(cardList)) {
                List<MbOrgUserIdcard> mbOrgUserIdcardList = new ArrayList<>();
                Date date = new Date();
                MbOrgUserIdcard mbOrgUserIdcard;
                for (UserIdCardFrontVo userIdCardFrontVo : cardList) {
                    mbOrgUserIdcard = new MbOrgUserIdcard();
                    mbOrgUserIdcard.setCardType(userIdCardFrontVo.getCtype());
                    mbOrgUserIdcard.setCardNo(userIdCardFrontVo.getcNumber());
                    mbOrgUserIdcard.setTimeLimit(userIdCardFrontVo.getcDate());
                    if (StringUtils.isNotBlank(userIdCardFrontVo.getPlaceOfIssue())) {
                        mbOrgUserIdcard.setPlaceOfIssue(userIdCardFrontVo.getPlaceOfIssue());
                    }
                    mbOrgUserIdcard.setEmployeeUid(uid);
                    mbOrgUserIdcard.setDeleteTime(new Date(0));
                    mbOrgUserIdcard.setDatachangeCreatetime(date);
                    mbOrgUserIdcard.setDatachangeLasttime(date);
                    mbOrgUserIdcardList.add(mbOrgUserIdcard);
                }
                organizationUserIdCardService.saveList(mbOrgUserIdcardList);
            }
            // 先删除用户常旅客卡，然后再插入现有证件
            organizationUserFfpService.deleteByUid(uid);
            List<UserFfpFrontVo> ffpList = request.getClkInfo();
            if (CollectionUtils.isNotEmpty(ffpList)) {
                List<MbOrgUserFfpinfo> mbOrgUserFfpinfoList = new ArrayList<>();
                Date date = new Date();
                for (UserFfpFrontVo userFfpFrontVo : ffpList) {
                    if (StringUtils.isBlank(userFfpFrontVo.getHkNumber()) || StringUtils.isBlank(userFfpFrontVo.getClkCode())) {
                        continue;
                    }
                    MbOrgUserFfpinfo mbOrgUserFfpinfo = new MbOrgUserFfpinfo();
                    mbOrgUserFfpinfo.setAirline(userFfpFrontVo.getHkNumber());
                    mbOrgUserFfpinfo.setFfpno(userFfpFrontVo.getClkCode());
                    mbOrgUserFfpinfo.setUid(uid);
                    mbOrgUserFfpinfo.setDatachangeCreatetime(date);
                    mbOrgUserFfpinfo.setIsDeleted(false);
                    mbOrgUserFfpinfo.setDatachangeLasttime(date);
                    mbOrgUserFfpinfoList.add(mbOrgUserFfpinfo);
                }
                organizationUserFfpService.saveList(mbOrgUserFfpinfoList);
            }
            // 更新新鲜度表用户部门
            MbFreshPassenger mbFreshPassenger = new MbFreshPassenger();
            mbFreshPassenger.setEmployeeUid(uid);
            mbFreshPassenger.setName(request.getUserName());
            String enName = "";
            if (StringUtils.isNotBlank(request.getFirstName()) || StringUtils.isNotBlank(request.getLastName())) {
                enName = (StringUtils.isNotBlank(request.getFirstName()) ? request.getFirstName() : "") + "/" + (StringUtils.isNotBlank(request.getLastName()) ? request.getLastName() : "");
            }
            mbFreshPassenger.setEnName(enName);
            freshPassengerService.updateEmployeeOrg(mbFreshPassenger);
            // 调用login接口，修改用户数据
            MbUserLoginVo mbUserLoginVo = new MbUserLoginVo();
            mbUserLoginVo.setUid(uid);
            mbUserLoginVo.setUserName(request.getUserName());
            mbUserLoginVo.setPhoneNum(request.getTelPhone());
            mbUserLoginVo.setCountryCode(request.getAreaCode());
            mbUserLoginVo.setEmail(request.getMailbox());
            userLoginService.saveOrUpdate(mbUserLoginVo, false,request.getIsSyncLoginPhone());

            if (Objects.nonNull(request.getRoleId()) && request.getRoleId() > 0) {
                UidOrgIdEntry identity = new UidOrgIdEntry();
                identity.setUid(uid);
                identity.setOrgId(request.getOrgId());
                userRoleService.clearLeft(Collections.singleton(new UidOrgIdEntry(uid, request.getOrgId())));
                userRoleService.insertOrUpdate(null, identity, request.getRoleId());
            }

            if (nameIsDiff) {
                approvalClientLoader.updateFlowTmpl(mbOrgEmployeeInfo.getUid(), mbOrgEmployeeInfo.getName());
            }
        } else if (2 == status) {
            // 删除
            flag = organizationEmployeeService.deleteByUid(uid);
            organizationUserIdCardService.deleteByEmployeeUid(uid);
            organizationUserFfpService.deleteByUid(uid);
            // 删除登录信息
            userLoginService.deleteByUid(uid);
            // 删除新鲜度中用户数据
            freshPassengerService.deleteEmployee(uid, null);

            userRoleService.clearLeft(Collections.singleton(new UidOrgIdEntry(uid, request.getOrgId())));

        }
        if (status == 1 || status == 0) {//更新缓存信息
            //更新缓存
            baseUserInfo.setAccountName(request.getUserName());
        }
        return JSONResult.success(new SaveEmpBaseInfoResponse(flag, 0, null, uid));
    }

    private void checkRequestParams(OperateEmployeeRequest request) {
        if (StringUtils.isBlank(request.getUserName())) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.UNAME_NULL);
        }
        if (StringUtils.isBlank(request.getUid())){
            throw new CorpBusinessException(OrganizationResponseCodeEnum.EMPLOYEE_CODE_CAN_NOT_BE_NULL);
        }
        request.setUid(request.getUid().trim());
    }

    /**
     * 添加前台用户判断信息是否相等
     *
     * @param exitedUser
     * @param request
     * @return
     */
    private boolean adjustBaseEmpInfo(MbOrgEmployeeInfo exitedUser, OperateEmployeeRequest request) {
        //基础信息
        if (!Objects.equals(exitedUser.getName(), request.getUserName()) || !Objects.equals(exitedUser.getGender(), request.getGender().equals("0") ? CommonConst.MAN : CommonConst.FEMALE)
                || !Objects.equals(exitedUser.getNationality(), request.getNationality())) {
            log.info("基本信息差异：{}, 原数据：{}", JsonUtils.toJsonString(exitedUser), JsonUtils.toJsonString(request));
            return false;
        }
        //证件信息
        // 补充证件信息
        // 证件信息
        List<MbOrgUserIdcard> cardList = organizationUserIdCardService.findByEmployeeUid(exitedUser.getUid());
        log.info("查询到的证件信息:{}", JsonUtils.toJsonString(cardList));
        Map<Integer, MbOrgUserIdcard> cardMap = cardList.stream().collect(Collectors.toMap(x -> x.getCardType(), x -> x, (k1, k2) -> k1));
        if (request.getcInfo().size() != cardList.size()) {
            return false;
        }
        MbOrgUserIdcard mbOrgUserIdcard = null;
        for (UserIdCardFrontVo userIdCardFrontVo : request.getcInfo()) {
            mbOrgUserIdcard = cardMap.get(userIdCardFrontVo.getCtype());
            if (mbOrgUserIdcard == null) {
                return false;
            }
            if (!userIdCardFrontVo.getcNumber().equals(mbOrgUserIdcard.getCardNo())) {
                return false;
            }
        }
        return true;
    }

    /**
     * 设置管理员日志soa
     */
    @RequestMapping("/setAdminLog")
    public JSONResult<List<OrgPostLogVo>> setAdminLog(@RequestParam(name = "uids") List<String> uids,
                                                      @RequestParam(name = "orgId") String orgId) {
        return JSONResult.success(organizationEmployeeService.queryAdminLog(uids, orgId));
    }
//
//    @RequestMapping("/findUidByNameAndOrgId")
//    public JSONResult<String> findUidByNameAndOrgId(@RequestBody QueryUidRequest request) {
//        if (request == null) {
//            return JSONResult.errorMsg("请求信息为空");
//        }
//        if (StringUtils.isEmpty(request.getName())) {
//            return JSONResult.errorMsg("用户名为空");
//
//        }
//        if (StringUtils.isEmpty(request.getOrgId())) {
//            return JSONResult.errorMsg("企业id为空");
//        }
//        String uId = null;
//        try {
//            uId = organizationEmployeeService.makeUserId(request.getOrgId(), request.getName());
//        } catch (Exception e) {
//            e.printStackTrace();
//            return JSONResult.errorMsg(e.getMessage());
//
//        }
//        return JSONResult.success(uId);
//    }

    /**
     * 根据职级id查询员工信息
     *
     * @param postIds
     * @return
     */
    @PostMapping("/listByPostIds")
    public JSONResult<List<OrgEmployeeVo>> listByPostIds(@RequestBody List<Long> postIds) {
        if (CollectionUtils.isEmpty(postIds)) {
            return JSONResult.errorMsg("postIds不能为空");
        }
        List<MbOrgEmployeeInfo> employeeInfoList = organizationEmployeeService.listByPostIds(postIds);
        if (CollectionUtils.isEmpty(employeeInfoList)) {
            return JSONResult.ok();
        }
        List<String> orgIds = employeeInfoList.stream().map(MbOrgEmployeeInfo::getOrgId).filter(StringUtils::isNotBlank).distinct().collect(Collectors.toList());
        List<MbOrgInfo> orgInfoList = organizationInfoService.listByOrgIds(orgIds);
        Map<String, MbOrgInfo> orgInfoMap = orgInfoList.stream().collect(Collectors.toMap(MbOrgInfo::getOrgId, Function.identity(), (e1, e2) -> e1));
        List<OrgEmployeeVo> result = employeeInfoList.stream().map(e -> {
            String orgId = e.getOrgId();
            MbOrgInfo orgInfo = orgInfoMap.get(orgId);
            if (orgInfo == null) {
                return null;
            }
            OrgEmployeeVo orgEmployeeVo = new OrgEmployeeVo();
            orgEmployeeVo.setOrgId(orgId);
            orgEmployeeVo.setOrgName(orgInfo.getName());
            orgEmployeeVo.setUid(e.getUid());
            orgEmployeeVo.setName(e.getName());
            return orgEmployeeVo;
        }).filter(Objects::nonNull).collect(Collectors.toList());
        return JSONResult.success(result);
    }

    /**
     * 根据角色Id获取用户信息
     * @param roleIds
     * @return
     */
    @PostMapping("/listByRoleIds")
    public JSONResult<List<OrgEmployeeVo>> listByRoleIds(@RequestBody List<Long> roleIds) {
        if (CollectionUtils.isEmpty(roleIds)) {
            return JSONResult.errorMsg("roleIds不能为空");
        }
        List<MbOrgEmployeeInfo> employeeInfoList = organizationEmployeeService.listByRoleIds(roleIds);
        if (CollectionUtils.isEmpty(employeeInfoList)) {
            return JSONResult.ok();
        }
        List<OrgEmployeeVo> result = new ArrayList<>();
        for(MbOrgEmployeeInfo mbOrgEmployeeInfo : employeeInfoList) {
            OrgEmployeeVo newOrgEmployeeVo = new OrgEmployeeVo();
            BeanUtils.copyProperties(mbOrgEmployeeInfo, newOrgEmployeeVo);
            result.add(newOrgEmployeeVo);
        }

        return JSONResult.success(result);
    }

    /**
     * 根据员工uid和orgId批量查询员工信息
     *
     * @param requestBo
     * @return
     */
    @PostMapping(value = "/listEmployeeInfo")
    public JSONResult<List<EmployeeInfoResponseBo>> listEmployeeInfo(@RequestBody @Valid List<EmployeeInfoRequestBo> requestBo) {
        log.info("查询员工信息request:{}", JsonUtils.toJsonString(requestBo));
        List<OrgUserInfoPk> pkList = requestBo.stream().map(e -> new OrgUserInfoPk(e.getUid(), e.getOrgId())).collect(Collectors.toList());
        return JSONResult.success(organizationEmployeeService.listEmployeeInfo(pkList));
    }

    @RequestMapping("/listUnAuditEmployee")
    public JSONResult<Page<OrgEmployeeVo>> listUnAuditEmployee(@RequestBody GetUnAuditEmployeeListRequest request) {
        String orgId = request.getOrgId();
        if (StringUtils.isBlank(orgId)) {
            return JSONResult.errorMsg("orgId参数缺失");
        }
        // 通过组织结构id查询出员工信息列表
        List<MbOrgEmployeeInfo> employeeInfoList = organizationEmployeeService.listUnAuditEmployee(request.getOrgId(), request.getPageNum(), request.getPageSize());
        if (CollectionUtils.isEmpty(employeeInfoList)) {
            return JSONResult.success(new Page<>(request.getPageNum(), request.getPageSize(), 0, 0L, new ArrayList<>()));
        }
        List<OrgEmployeeVo> returnList = new ArrayList<>();
        for (MbOrgEmployeeInfo mbOrgEmployeeInfo : employeeInfoList) {
            OrgEmployeeVo orgEmployeeVo = new OrgEmployeeVo();
            orgEmployeeVo.setUid(mbOrgEmployeeInfo.getUid());
            orgEmployeeVo.setName(mbOrgEmployeeInfo.getName());
            orgEmployeeVo.setEmail(mbOrgEmployeeInfo.getEmail());
            orgEmployeeVo.setMobilePhone(mbOrgEmployeeInfo.getMobilePhone());
            returnList.add(orgEmployeeVo);
        }
        PageInfo<OrgEmployeeVo> page = new PageInfo<>(returnList);
        return JSONResult.success(new Page<>(page.getPageNum(), page.getPageSize(), page.getPages(), page.getTotal(), returnList));
    }

    /**
     * 新增人员身份信息
     */
    @RequestMapping("/saveUserDignity")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public JSONResult<Boolean> saveUserDignity(@RequestBody OperatorUserDignityRequest addUserDignityRequest) {
        if(StringUtils.isBlank(addUserDignityRequest.getOrgId())){
            throw new CorpBusinessException(OrganizationResponseCodeEnum.ORG_ID_NULL);
        }
        if(StringUtils.isBlank(addUserDignityRequest.getUid())){
            throw new CorpBusinessException(OrganizationResponseCodeEnum.UID_NULL);
        }
        // 去掉空格
        addUserDignityRequest.setOrgId(addUserDignityRequest.getOrgId().trim());
        addUserDignityRequest.setUid(addUserDignityRequest.getUid().trim());
        //查询是否存在
        MbUserOrgRelation orgData = userOrgRelationService.find(addUserDignityRequest.getOrgId(), addUserDignityRequest.getUid());
        if (orgData != null) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.USER_ALREADY_EXISTS);
        }
        // 保存关系表。
        MbUserOrgRelation mbUserOrgRelation = new MbUserOrgRelation();
        mbUserOrgRelation.setOrgId(addUserDignityRequest.getOrgId());
        mbUserOrgRelation.setUid(addUserDignityRequest.getUid());
        mbUserOrgRelation.setStatus(UserOrgRelationStatusEnum.NORMAL.getStatus());
        mbUserOrgRelation.setIsLeader(addUserDignityRequest.getIsLeader());
        mbUserOrgRelation.setPostId(addUserDignityRequest.getPostId());
        mbUserOrgRelation.setVipLevel(addUserDignityRequest.getVipLevel());
        boolean relationFlag = userOrgRelationService.save(mbUserOrgRelation);
        //插入角色
        Long roleId = addUserDignityRequest.getRoleId();
        if (roleId != null) {
            UidOrgIdEntry uidOrgIdEntry = new UidOrgIdEntry();
            uidOrgIdEntry.setUid(addUserDignityRequest.getOrgId());
            uidOrgIdEntry.setOrgId(addUserDignityRequest.getUid());
            userRoleService.insertOrUpdateByUidAndOrgId(uidOrgIdEntry, addUserDignityRequest.getRoleId());
        }
        if (!relationFlag) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.USER_CREATE_ERROR);
        }
        return JSONResult.success(relationFlag);
    }

    /**
     * 查看人员身份信息
     */
    @RequestMapping("/queryUserDignity")
    @ResponseBody
    public JSONResult<UserDignityVo> queryUserDignity(@RequestBody OperatorUserDignityRequest updateUserDignityRequest) {
        UserDignityVo userDignityVo = userDignity(updateUserDignityRequest.getOrgId(), updateUserDignityRequest.getUid());
        return JSONResult.success(userDignityVo);
    }

    /**
     * 查看人员身份信息
     */
    @RequestMapping("/queryUserDignityList")
    @ResponseBody
    public JSONResult<List<UserDignityVo>> queryUserDignityList(@RequestBody OperatorUserDignityRequest updateUserDignityRequest) {
        return JSONResult.success(userDignity(updateUserDignityRequest.getUid()));
    }

    /**
     * 查询组织下的身份
     *
     * @param orgId
     * @param uid
     * @return
     */
    private UserDignityVo userDignity(String orgId, String uid) {
        if (StringUtils.isBlank(orgId) || StringUtils.isBlank(uid)) {
            return null;
        }
        uid = uid.trim();
        //查询是否存在
        MbUserOrgRelation data = userOrgRelationService.find(orgId, uid);
        if (data == null) {
            return null;
        }
        UserDignityVo userDignityVo = new UserDignityVo();
        //查询角色
        List<MbRole> roleInfoList = roleService.findByUidAndOrgId(uid, orgId);
        log.info("roleInfoList:{}", JsonUtils.toJsonString(roleInfoList));
        if (CollectionUtils.isNotEmpty(roleInfoList)) {
            userDignityVo.setRoleId(roleInfoList.get(0).getId());
            userDignityVo.setRoleName(roleInfoList.get(0).getName());
        }
        List<OrgInfoVo> orgInfoList = organizationInfoService.getOrgInfoList(orgId, true);
        List<String> returnList = null;
        if (CollectionUtils.isNotEmpty(orgInfoList)) {
            returnList = orgInfoList.stream().sorted(Comparator.comparing(OrgInfoVo::getLevel))
                    .map(OrgInfoVo::getName)
                    .collect(Collectors.toList());
            StringBuilder nameBuffer = new StringBuilder();
            for (String name : returnList) {
                nameBuffer.append(name).append(">");
            }
            userDignityVo.setOrgDesc(nameBuffer.substring(0, nameBuffer.length() - 1));
        }
        BeanUtils.copyProperties(data, userDignityVo, "isLeader");
        userDignityVo.setIsLeader(data.getIsLeader() == 1);
        //查询上级负责人
        JSONResult<List<OrgEmployeeVo>> result = findLeaderByOrgId(orgId);
        List<OrgEmployeeVo> leaderList = result.getData();
        if (CollectionUtils.isNotEmpty(leaderList)) {
            userDignityVo.setLeaderName(leaderList.stream().map(OrgEmployeeVo::getName).collect(Collectors.joining(",")));
        }
        //查询上级姓名
        MbOrgEmployeeInfo mbOrgEmployeeInfo = organizationEmployeeService.findByUid(userDignityVo.getManageUid());
        userDignityVo.setManageName(Optional.ofNullable(mbOrgEmployeeInfo).map(MbOrgEmployeeInfo::getName).orElse(null));
        // 岗位信息
        Optional.ofNullable(employeeJobRelationMapper.getByUid(uid)).map(item -> jobMapper.getById(item.getJobId())).ifPresent(item -> {
            userDignityVo.setJobId(item.getId());
            userDignityVo.setJobName(item.getName());
            userDignityVo.setJobCode(item.getCode());
        });
        return userDignityVo;
    }

    /**
     * 查询所有身份
     *
     * @param uid
     * @return
     */
    private List<UserDignityVo> userDignity(String uid) {
        if(StringUtils.isBlank(uid)){
            throw new CorpBusinessException(OrganizationResponseCodeEnum.UID_NULL);
        }
        uid = uid.trim();
        //查询是否存在
        List<MbUserOrgRelation> data = userOrgRelationService.listByUid(uid);
        if (CollectionUtils.isEmpty(data)) {
            return null;
        }
        Set<UidOrgIdEntry> uidOrgIdEntries = new HashSet<>();
        UidOrgIdEntry uidOrgIdEntry = null;
        for (MbUserOrgRelation userOrgRelation : data) {
            uidOrgIdEntry = new UidOrgIdEntry();
            uidOrgIdEntry.setUid(userOrgRelation.getUid());
            uidOrgIdEntry.setOrgId(userOrgRelation.getOrgId());
            uidOrgIdEntries.add(uidOrgIdEntry);
        }
        Map<UidOrgIdEntry, List<UserRole>> roleMap = userRoleService.queryRoles(uidOrgIdEntries);
        List<UserDignityVo> userDignityList = new ArrayList<>();
        UserDignityVo userDignityVo = null;
        for (MbUserOrgRelation temp : data) {
            userDignityVo = new UserDignityVo();
            if (roleMap != null) {
                List<UserRole> list = roleMap.get(new UidOrgIdEntry(temp.getUid(), temp.getOrgId()));
                if (CollectionUtils.isNotEmpty(list)) {
                    userDignityVo.setRoleName(list.get(0).getRoleName());
                    userDignityVo.setRoleId(list.get(0).getRoleId());
                }
            }
            BeanUtils.copyProperties(temp, userDignityVo, "isLeader");
            userDignityVo.setIsLeader(temp.getIsLeader() == 1);
            userDignityList.add(userDignityVo);
        }
        return userDignityList;
    }

    /**
     * 更新人员身份信息
     */
    @RequestMapping("/updateUserDignity")
    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
    public JSONResult<Boolean> updateUserDignity(@RequestBody OperatorUserDignityRequest updateUserDignityRequest) {
        if(StringUtils.isBlank(updateUserDignityRequest.getOrgId())){
            throw new CorpBusinessException(OrganizationResponseCodeEnum.ORG_ID_NULL);
        }
        if(StringUtils.isBlank(updateUserDignityRequest.getUid())){
            throw new CorpBusinessException(OrganizationResponseCodeEnum.UID_NULL);
        }
        updateUserDignityRequest.setOrgId(updateUserDignityRequest.getOrgId().trim());
        updateUserDignityRequest.setUid(updateUserDignityRequest.getUid().trim());
        //查询是否存在
        MbUserOrgRelation oldData = userOrgRelationService.find(updateUserDignityRequest.getOrgId(), updateUserDignityRequest.getUid());
        if (oldData == null) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.USER_INFO_DONT_EXISTS);
        }
        // 保存关系表。默认审批中状态
        MbUserOrgRelation mbUserOrgRelation = new MbUserOrgRelation();
        mbUserOrgRelation.setOrgId(updateUserDignityRequest.getOrgId());
        mbUserOrgRelation.setUid(updateUserDignityRequest.getUid());
        mbUserOrgRelation.setStatus(oldData.getStatus());
        mbUserOrgRelation.setIsLeader(updateUserDignityRequest.getIsLeader());
        mbUserOrgRelation.setPostId(updateUserDignityRequest.getPostId());
        mbUserOrgRelation.setVipLevel(updateUserDignityRequest.getVipLevel());
        mbUserOrgRelation.setManageUid(updateUserDignityRequest.getManageUid());
        //更新角色
        UidOrgIdEntry uidOrgIdEntry = new UidOrgIdEntry();
        uidOrgIdEntry.setUid(updateUserDignityRequest.getUid());
        uidOrgIdEntry.setOrgId(updateUserDignityRequest.getOrgId());
        if (updateUserDignityRequest.getRoleId() != null) {
            userRoleService.insertOrUpdateByUidAndOrgId(uidOrgIdEntry, updateUserDignityRequest.getRoleId());
        } else {
            Set<UidOrgIdEntry> ids = new HashSet<>();
            ids.add(uidOrgIdEntry);
            userRoleService.clearLeft(ids);
        }
        mbUserOrgRelation.setId(oldData.getId());
        if(mbUserOrgRelation.getPostId() == null){
            userOrgRelationService.cleanPostIdByUidAndOrgId(updateUserDignityRequest.getUid(), updateUserDignityRequest.getOrgId());
        }
        boolean relationFlag = userOrgRelationService.update(mbUserOrgRelation);
        if (!relationFlag) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.USER_CREATE_ERROR);
        }
        roleResourceManager.delUserRoleId(updateUserDignityRequest.getUid() + updateUserDignityRequest.getOrgId());
        // 更新岗位
        Long jobId = updateUserDignityRequest.getJobId();
        if (jobId != null) {
            employeeJobRelationMapper.createOrUpdate(new EmployeeJobRelationDo(updateUserDignityRequest.getUid(), jobId));
        }
        // 删除岗位
        else {
            employeeJobRelationMapper.removeByUid(updateUserDignityRequest.getUid());
        }
        return JSONResult.success(relationFlag);
    }

    @RequestMapping("/findEmployeeDetailByUid")
    @ResponseBody
    public JSONResult<OperateEmployeeRequest> findEmployeeDetailByUid(@RequestBody GetEmployeeDetailRequest request) {
        String uid = request.getUid();
        if (StringUtils.isBlank(uid)) {
            return JSONResult.errorMsg("uid不能为空");
        }
        uid = uid.trim();
        MbOrgEmployeeInfo mbOrgEmployeeInfo = organizationEmployeeService.findByUid(uid);
        OperateEmployeeRequest operateEmployeeRequest = new OperateEmployeeRequest();
        operateEmployeeRequest.setUserName(mbOrgEmployeeInfo.getName());
        operateEmployeeRequest.setLastName(mbOrgEmployeeInfo.getLastEnName());
        operateEmployeeRequest.setFirstName(mbOrgEmployeeInfo.getFirstEnName());
        operateEmployeeRequest.setOrgId(mbOrgEmployeeInfo.getOrgId());
        operateEmployeeRequest.setTelPhone(mbOrgEmployeeInfo.getMobilePhone());
        operateEmployeeRequest.setMailbox(mbOrgEmployeeInfo.getEmail());
        operateEmployeeRequest.setCreditCardNumbers(mbOrgEmployeeInfo.getCreditCardNumbers());
        operateEmployeeRequest.setEmployeeType(mbOrgEmployeeInfo.getEmployeeType());
        operateEmployeeRequest.setCorporateEntity(mbOrgEmployeeInfo.getCorporateEntity());
        // 是否读取nameInfo的数据,T:读取  F:不读取
        boolean nameInfoReadSwitch = "T".equalsIgnoreCase(organizationApollo.getNameInfoReadSwitch());
        if(nameInfoReadSwitch && StrUtil.isNotBlank(mbOrgEmployeeInfo.getNameInfo())){
            NameInfoBo nameInfoBo = JsonUtils.parse(mbOrgEmployeeInfo.getNameInfo(), NameInfoBo.class);
            operateEmployeeRequest.setSurname(nameInfoBo.getSurname());
            operateEmployeeRequest.setGivenname(nameInfoBo.getGivenname());
            operateEmployeeRequest.setFullEnName(com.corpgovernment.organization.util.StrUtils.processFullEnName(nameInfoBo.getSurname(),nameInfoBo.getGivenname()));
            operateEmployeeRequest.setFullName(nameInfoBo.getFullName());
            operateEmployeeRequest.setNationality(nameInfoBo.getNationality());
        }else{
            operateEmployeeRequest.setSurname(mbOrgEmployeeInfo.getLastEnName());
            operateEmployeeRequest.setGivenname(mbOrgEmployeeInfo.getFirstEnName());
            operateEmployeeRequest.setFullEnName(com.corpgovernment.organization.util.StrUtils.processFullEnName(mbOrgEmployeeInfo.getLastEnName(),mbOrgEmployeeInfo.getFirstEnName()));
            operateEmployeeRequest.setFullName(mbOrgEmployeeInfo.getName());
            operateEmployeeRequest.setNationality(mbOrgEmployeeInfo.getNationality());
        }
        String gender = mbOrgEmployeeInfo.getGender();
        if (StringUtils.isNotBlank(gender)) {
            operateEmployeeRequest.setGender(mbOrgEmployeeInfo.getGender().equals(CommonConst.MAN) ? "0" : "1");
        }
        operateEmployeeRequest.setBirthday(mbOrgEmployeeInfo.getBirthday());
        String valid = mbOrgEmployeeInfo.getValid();
        // 查询用户状态,用户状态在表mb_user_org_relation.status 身份状态 0拒绝，1正常，2待审核，3离职
        List<MbUserOrgRelation> mbUserOrgRelationList = null;
        if(StrUtil.isNotBlank(mbOrgEmployeeInfo.getUid()) ){
            mbUserOrgRelationList = iUserOrgRelationService.findByUid(mbOrgEmployeeInfo.getUid());
        }
        if(CollectionUtil.isNotEmpty(mbUserOrgRelationList)){
            operateEmployeeRequest.setStatus(mbUserOrgRelationList.get(0).getStatus());
        }
        // 补充证件信息
        // 证件信息
        List<MbOrgUserIdcard> cardList = organizationUserIdCardService.findByEmployeeUid(uid);
        List<UserIdCardFrontVo> cardVoList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(cardList)) {
            for (MbOrgUserIdcard mbOrgUserIdcard : cardList) {
                UserIdCardFrontVo userIdCardFrontVo = new UserIdCardFrontVo();
                userIdCardFrontVo.setCtype(mbOrgUserIdcard.getCardType());
                userIdCardFrontVo.setcNumber(mbOrgUserIdcard.getCardNo());
                userIdCardFrontVo.setcDate(mbOrgUserIdcard.getTimeLimit());
                userIdCardFrontVo.setPlaceOfIssue(mbOrgUserIdcard.getPlaceOfIssue());
                userIdCardFrontVo.setCertificates(getCardTypeList());
                cardVoList.add(userIdCardFrontVo);
            }
        }
        // ffp信息
        List<MbOrgUserFfpinfo> ffpList = organizationUserFfpService.listByUid(uid);
        List<UserFfpFrontVo> ffpFrontVoList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(ffpList)) {
            for (MbOrgUserFfpinfo mbOrgUserFfpinfo : ffpList) {
                UserFfpFrontVo userFfpFrontVo = new UserFfpFrontVo();
                userFfpFrontVo.setHkNumber(mbOrgUserFfpinfo.getAirline());
                userFfpFrontVo.setClkCode(mbOrgUserFfpinfo.getFfpno());
                ffpFrontVoList.add(userFfpFrontVo);
            }
        }
        operateEmployeeRequest.setcInfo(cardVoList);
        operateEmployeeRequest.setClkInfo(ffpFrontVoList);
        operateEmployeeRequest.setAreaCode(mbOrgEmployeeInfo.getAreaCode());
        operateEmployeeRequest.setUid(mbOrgEmployeeInfo.getUid());
        //身份信息
        UserDignityVo userDignityVo = userDignity(request.getOrgId(), uid);
        operateEmployeeRequest.setUserDignityVo(userDignityVo);
        // 岗位信息
        Optional.ofNullable(employeeJobRelationMapper.getByUid(uid)).map(item -> jobMapper.getById(item.getJobId())).ifPresent(item -> {
            operateEmployeeRequest.setJobId(item.getId());
            operateEmployeeRequest.setJobName(item.getName());
            operateEmployeeRequest.setJobCode(item.getCode());
        });
        return new JSONResult<>(operateEmployeeRequest);
    }

    /**
     * 根据uid查询员工以及用户部门信息
     *
     * @param uid
     * @return
     */
    @PostMapping("/findEmpAndOrgByUid")
    public JSONResult<SearchCorpEmpResponse> findEmpAndOrgByUid(@RequestParam String uid) {
        SearchCorpEmpResponse searchCorpEmpResponses = organizationEmployeeService.findEmpAndOrgByUid(uid);
        return JSONResult.success(searchCorpEmpResponses);
    }

    @PostMapping(value = "/findByUid")
    public JSONResult<EmployeeInfoBo> findByUid(@RequestParam String uid) {
        MbOrgEmployeeInfo employeeInfo = organizationEmployeeService.findByUid(uid);
        if (employeeInfo == null) {
            return JSONResult.ok();
        }
        EmployeeInfoBo employeeInfoBo = new EmployeeInfoBo();
        BeanUtils.copyProperties(employeeInfo, employeeInfoBo);
        return JSONResult.success(employeeInfoBo);
    }

    @PostMapping(value = "/listByUids")
    public JSONResult<List<UserOrgRelation>> listByUids() {
        List<MbUserOrgRelation> mbUserOrgRelations = userOrgRelationService.listByUids();
        List<UserOrgRelation> result = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(mbUserOrgRelations)) {
            for (MbUserOrgRelation orgRelation : mbUserOrgRelations) {
                UserOrgRelation userOrgRelation = new UserOrgRelation();
                userOrgRelation.setOrgId(orgRelation.getOrgId());
                userOrgRelation.setUid(orgRelation.getUid());
                userOrgRelation.setIsLeader(orgRelation.getIsLeader());
                userOrgRelation.setStatus(orgRelation.getStatus());
                userOrgRelation.setPostId(orgRelation.getPostId());
                result.add(userOrgRelation);
            }
        }
        return JSONResult.success(result);
    }

    @PostMapping(value = "/listUserOrgRelationByUids")
    JSONResult<List<UserOrgRelation>> listUserOrgRelationByUids(@RequestBody List<String> uids){
        List<MbUserOrgRelation> mbUserOrgRelations = userOrgRelationService.listByUids(uids);
        List<UserOrgRelation> result = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(mbUserOrgRelations)) {
            for (MbUserOrgRelation orgRelation : mbUserOrgRelations) {
                UserOrgRelation userOrgRelation = new UserOrgRelation();
                userOrgRelation.setOrgId(orgRelation.getOrgId());
                userOrgRelation.setUid(orgRelation.getUid());
                userOrgRelation.setIsLeader(orgRelation.getIsLeader());
                userOrgRelation.setStatus(orgRelation.getStatus());
                userOrgRelation.setPostId(orgRelation.getPostId());
                result.add(userOrgRelation);
            }
        }
        return JSONResult.success(result);
    }

    /**
     * 查询公司部门下所以员工 不穿透子公司
     *
     * @param request
     * @return
     */
    @PostMapping(value = "/selectEmployeeByCorpId")
    public JSONResult<List<SearchCorpEmpResponse>> selectEmployeeByCorpId(@RequestBody SearchCorpEmpRequest request, BaseUserInfo baseUserInfo) {
        if (StringUtils.isEmpty(request.getCorpId())) {
            request.setCorpId(baseUserInfo.getCorpId());
        }
        // 接口支持全集团查询类型
        boolean findWholeGroup = WholeGroupQueryEnum.APPROVE.getCode().equals(request.getWholeGroupQuery())
                && organizationApollo.enableApproveShowAllOrg();
        List<MbOrgInfo> mbOrgInfos = null;
        if(findWholeGroup){
            mbOrgInfos = organizationInfoService.listAll();
        } else {
            mbOrgInfos = organizationInfoService.listAllDepartments(request.getCorpId(), false);
        }
        List<String> orgIds = mbOrgInfos.stream().map(MbOrgInfo::getOrgId).collect(Collectors.toList());
        orgIds.add(request.getCorpId());
        List<SearchCorpEmpResponse> orgEmployeeVos = organizationEmployeeService.selectEmployeeByOrgIds(orgIds);
        if (StringUtils.isNotBlank(request.getName())) {
            orgEmployeeVos = orgEmployeeVos.stream().filter(item -> item.getName().contains(request.getName())).distinct().collect(Collectors.toList());
        }
        List<MbUserRole> mbUserRoles = userRoleService.searchBgIsBackground(false);
        Map<String, List<MbUserRole>> uidMap = mbUserRoles.stream().filter(Objects::nonNull).collect(Collectors.groupingBy(MbUserRole::getUid));
        orgEmployeeVos.forEach(item -> {
            List<MbUserRole> roles = uidMap.get(item.getUid());
            if (CollectionUtils.isNotEmpty(roles)) {
                item.setRoleId(roles.get(0).getRoleId());
                item.setRoleName(roles.get(0).getRoleName());
            }
        });
        orgEmployeeVos = orgEmployeeVos.stream().distinct().collect(Collectors.toList());
        if (request.getIsExcludeMe() != null && request.getIsExcludeMe()) {
            orgEmployeeVos = orgEmployeeVos.stream().filter(e -> !Objects.equals(e.getUid(), baseUserInfo.getUid())).collect(Collectors.toList());
        }

        return JSONResult.success(orgEmployeeVos);
    }

    /**
     * 查询公司部门下所有员工，以及员工所在的所有部门（一个员工是可以在多个公司，多个部门任职的）
     *
     * @param request
     * @return
     */
    @PostMapping(value = "/selectAgentPerson")
    public JSONResult<List<AgentPersonResponse>> selectAgentPerson(@RequestBody SearchCorpEmpRequest request, BaseUserInfo baseUserInfo) {
        List<SearchCorpEmpResponse> list = this.selectEmployeeByCorpId(request, baseUserInfo).getData();
        if (CollectionUtils.isEmpty(list)) {
            return JSONResult.ok();
        }
        List<AgentPersonResponse> responseList = list.stream().map(e -> {
            AgentPersonResponse agentPersonResponse = new AgentPersonResponse();
            agentPersonResponse.setUid(e.getUid());
            agentPersonResponse.setName(e.getName());
            // 根据UID查询当前员工所在的所有部门（一个员工可以在多个部门任职,可以有多个身份）
            List<OrgDTO> orgDTOS = CollectionUtils.isEmpty(OrganizationUtils.genUserOrgInfo(e.getUid()).get(2)) ? OrganizationUtils.genUserOrgInfo(e.getUid()).get(1) : OrganizationUtils.genUserOrgInfo(e.getUid()).get(2);
            List<AgentPersonResponse.OrgInfo> orgInfos = orgDTOS.stream().map(m -> {
                AgentPersonResponse.OrgInfo orgInfo = new AgentPersonResponse.OrgInfo();
                orgInfo.setOrgId(m.getDeptId());
                orgInfo.setOrgName(m.getDeptName());
                return orgInfo;
            }).collect(Collectors.toList());
            agentPersonResponse.setOrgInfos(orgInfos);
            return agentPersonResponse;
        }).collect(Collectors.toList());
        return JSONResult.success(responseList);
    }

    /**
     * 更新用户信息
     *
     * @param request
     * @return
     */
    @RequestMapping("/updateByUid")
    public JSONResult<UpdateEmployeeResponseBO> updateByUid(@RequestBody UpdateEmployeeRequestBO request) {
        return JSONResult.success(organizationEmployeeService.updateByUid(request));
    }

    @RequestMapping("/updateEmployeeTypeByUid")
    public JSONResult<UpdateEmployeeResponseBO> updateEmployeeTypeByUid(@RequestParam(name = "employeeType") Integer employeeType, @RequestParam(name = "ids") List<String> ids){
        log.info("执行organization的updateEmployeeType方法");
        return JSONResult.success(organizationEmployeeService.updateEmployeeTypeByUid(employeeType, ids));
    }

    @RequestMapping("/findManageFuzzy")
    public JSONResult<List<MbOrgEmployeeInfo>> findManageFuzzy(@RequestBody FindManageFuzzyRequestBO request){
        return JSONResult.success(organizationEmployeeService.findManageFuzzy(request));
    }

    /**
     * 模糊搜索查询当前登录用户权限下所有员工信息
     *
     * @param request
     * @return
     */
    @ApiOperation("查询登录用户数据权限下所有的员工信息")
    @PostMapping("/queryEmployeeWithPermission")
    public JSONResult<QueryEmployeeInfoWithPermissionResponse> queryEmployeeWithPermission(
            @RequestBody QueryEmployeeInfoWithPermissionRequest request) {
        return JSONResult.success(organizationEmployeeService.queryEmployeeWithPermission(request));
    }

    @PostMapping("/listByJobIdList")
    public JSONResult<List<OrgEmployeeVo>> listByJobIdList(@RequestParam("jobIdList") List<Long> jobIdList) {
        if (CollectionUtils.isEmpty(jobIdList)) {
            return new JSONResult<>(null);
        }
        List<EmployeeJobRelationDo> employeeJobRelationDoList = employeeJobRelationMapper.listByJobIdList(jobIdList);
        log.info("岗位员工信息 employeeJobRelationDoList={}", employeeJobRelationDoList);
        if (CollectionUtils.isEmpty(employeeJobRelationDoList)) {
            return new JSONResult<>(null);
        }
        List<String> uidList = employeeJobRelationDoList.stream().map(EmployeeJobRelationDo::getUid).collect(Collectors.toList());
        // 获取员工信息
        List<MbOrgEmployeeInfo> mbOrgEmployeeInfoList = organizationEmployeeService.listByUids(uidList);
        log.info("获取员工信息 mbOrgEmployeeInfoList={}", mbOrgEmployeeInfoList);
        if (CollectionUtils.isEmpty(mbOrgEmployeeInfoList)) {
            return new JSONResult<>(null);
        }
        List<EmployeeByUidRequestVo> request = mbOrgEmployeeInfoList.stream().map(item -> {
            EmployeeByUidRequestVo employeeByUidRequestVo = new EmployeeByUidRequestVo();
            employeeByUidRequestVo.setEmployeeType(item.getEmployeeType());
            employeeByUidRequestVo.setUid(item.getUid());
            return employeeByUidRequestVo;
        }).collect(Collectors.toList());
        List<EmployeeInfoVo> employeeInfoByUidList = organizationEmployeeService.getEmployeeInfoByUidList(request);
        log.info("员工信息 employeeInfoByUidList={}", employeeInfoByUidList);
        if (CollectionUtils.isEmpty(employeeInfoByUidList)) {
            return new JSONResult<>(null);
        }
        List<OrgEmployeeVo> result = new ArrayList<>();
        for(EmployeeInfoVo item : employeeInfoByUidList) {
            OrgEmployeeVo orgEmployeeVo = new OrgEmployeeVo();
            orgEmployeeVo.setUid(item.getUid());
            orgEmployeeVo.setName(item.getName());
            orgEmployeeVo.setOrgName(item.getOrgName());
            orgEmployeeVo.setOrgId(item.getOrgId());
            result.add(orgEmployeeVo);
        }
        return new JSONResult<>(result);
    }


    @RequestMapping("/getEmployeeInfoByUidOrNonEmpId")
    public JSONResult<List<EmployeeInfoVo>> getEmployeeInfoByUidOrNonEmpId(@RequestBody List<EmployeeByUidRequestVo> request){
        JSONResult<List<EmployeeInfoVo>> listJSONResult = JSONResult.success(organizationEmployeeService.getEmployeeInfoByUidList(request));
        // 内部soa接口，无需脱敏处理
        SecurityContext.setSecurityAccessible(true);
        return listJSONResult;
    }

    @RequestMapping("/refreshEmployeeBirthAndGender")
    public JSONResult<Boolean> refreshEmployeeBirthAndGender(@RequestBody String request){
        return JSONResult.success(organizationEmployeeService.refreshEmployeeBirthAndGender(request));
    }

    @PostMapping("/listEmployeeByCondition")
    public JSONResult<ListEmployeeByConditionResponse> listEmployeeByCondition(@RequestBody ListEmployeeByConditionRequest request){
        return JSONResult.success(organizationEmployeeService.listEmployeeByCondition(request));
    }
}
